Option Explicit
Sub mergeEqualCells()
' Define constants.
Const wsName As String = "Sheet1"
Const FirstCell As String = "A1"
Const Offs As Long = 2
' Define workbook.
Dim wb As Workbook
Set wb = ThisWorkbook
' Define Source Column Range.
' Define worksheet
Dim ws As Worksheet
Set ws = wb.Worksheets(wsName)
' Define Source Column Range.
Dim rng As Range
Set rng = ws.Range(FirstCell)
Dim Col As Long
Col = rng.Column
Dim FirstRow As Long
FirstRow = rng.Row
Dim LastRow As Long
LastRow = ws.Cells(ws.Rows.Count, Col).End(xlUp).Row
If LastRow < FirstRow Then
GoTo ProcExit
End If
Set rng = ws.Columns(rng.Column).Resize(LastRow)
' Write values from Source Column Range to Data Array.
Dim Data As Variant
If rng.Cells.Count > 1 Then
Data = rng.Value
Else
ReDim Data(1 To 1, 1 To 1)
Data(1, 1) = rng.Value
End If
' Prepare to write from Data Array to Target Column Range.
Dim First As Long
First = FirstRow
Dim CurVal As Variant
CurVal = ws.Cells(First, Col).Value
Dim CurSize As Long
CurSize = 1
Dim i As Long
Application.ScreenUpdating = False
With rng.Offset(, Offs)
.Clear
' Or something like the following combination.
'.UnMerge
'.ClearContents
End With
' Write from Data Array to Target Column Range.
For i = FirstRow + 1 To LastRow
If Data(i, 1) <> Data(i - 1, 1) Then
With ws.Cells(First, Col + Offs)
.Value = CurVal
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
If CurSize > 1 Then
With .Resize(CurSize)
.Merge
End With
End If
End With
First = i
CurVal = ws.Cells(First, Col).Value
CurSize = 1
Else
CurSize = CurSize + 1
End If
Next i
With ws.Cells(First, Col + Offs)
.Value = CurVal
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
If CurSize > 1 Then
With .Resize(CurSize)
.Merge
End With
End If
End With
Application.ScreenUpdating = True
' Inform user.
MsgBox "Cells merged.", vbInformation, "Success"
ProcExit:
End Sub