I need a macro that will merge cells that have equal adjacent values in a column. For example if I have a worksheet set up like this:
Column A
The output I want is this:
Column A
However, the following code won't work because it will merge the first grouping of rows containing the word, "Teach" with the other grouping containing the word "Teach".
This macro fails in this application because of how CountIf() works relative to what I need a function to do. I essentially need a macro that will iterate through the rows of a column, merging cells that contain an equivalent value to the cell above the current row. If there is a match, then merge, otherwise move on to the next row. I'm hoping there is a straightforward way to use a derivative of the function above that doesn't utilize CountIf().
Column A
Teach
Teach
Old
Dog
Dog
New
New
Tricks
Tricks
Teach
Teach
Teach
The output I want is this:
Column A
Teach
[Cell Merged With 1 Cell Above]
Old
Dog
[Cell Merged With 1 Cell Above]
New
[Cell Merged With 1 Cell Above]
Tricks
[Cell Merged With 1 Cell Above]
Teach
[Cell Merged With Cells Above]
[Cell Merged With Cells Above]
However, the following code won't work because it will merge the first grouping of rows containing the word, "Teach" with the other grouping containing the word "Teach".
Code:
Sub MergeColA()
Dim c As Range, A As Range
Dim RwsToMrg As Long
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
Set A = Range(Cells(1,1), Cells(Rows.Count,1).End(xlUp))
' Eliminate trailing whitespace in the input
For Each c in A
c.Value = Trim(c.Value)
Next c
For Each c in A
RwsToMrg = Application.WorksheetFunction.CountIf(A,c)
If RwsToMrg > 1 Then
With c.Resize(RwsToMrg,1)
.Merge
.VerticalAlignment = xlTop
End With
End If
Next c
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
End Sub
This macro fails in this application because of how CountIf() works relative to what I need a function to do. I essentially need a macro that will iterate through the rows of a column, merging cells that contain an equivalent value to the cell above the current row. If there is a match, then merge, otherwise move on to the next row. I'm hoping there is a straightforward way to use a derivative of the function above that doesn't utilize CountIf().