如下图,合并第一列相邻区域的相同单元格及逆操作。
合并第一列相邻区域的相同单元格的过程代码
Sub MergeSameCells()
Dim lRow As Integer
Dim i As Long
Application.DisplayAlerts = False
With ActiveSheet
lRow = .Range("A" & Cells.Rows.Count).End(xlUp).Row
For i = lRow To 2 Step -1
If .Cells(i, 1).Value = .Cells(i - 1, 1).Value Then
.Range(.Cells(i - 1, 1), .Cells(i, 1)).Merge
End If
Next
End With
Application.DisplayAlerts = True
End Sub
代码分析
通过一个for循环,从最后一个非空单元格开始,比较相邻两个单元格是否相同,相同则合并;
过程执行后效果如下:
逆操作,也就是取消合并,并填充空白单元格
Sub unMergeValue()
Dim s As String
Dim i As Long
Dim j As Long
Dim cnt As Integer
j = Range("A" & Cells.Rows.Count).End(xlUp).Row
For i = 2 To j
With Cells(i, 1)
s = .Value
cnt = .MergeArea.Count
.UnMerge
.Resize(cnt, 1).Value = s
End With
i = i + cnt - 1
Next
End Sub
代码分析:
通过一个for循环,从第二行开始,循环内执行以下操作:
取得合并单元格的值S;
逐一取得合并单元格合并的单元格个数(MergeArea.Count);
合并单元格取消合并(UnMerge);
通过resize方法重新取得合并区域,并全部赋值为S;