如下图,合并第一列相邻区域的相同单元格及逆操作。
1498291834797378.jpg
合并第一列相邻区域的相同单元格的过程代码Sub MergeSameCells()Dim lRow As IntegerDim i As LongApplication.DisplayAlerts = FalseWith ActiveSheetlRow = .Range("A" & Cells.Rows.Count).End(xlUp).RowFor i = lRow To 2 Step -1If .Cells(i, 1).Value = .Cells(i - 1, 1).Value Then.Range(.Cells(i - 1, 1), .Cells(i, 1)).MergeEnd IfNextEnd WithApplication.DisplayAlerts = TrueEnd Sub代码分析通过一个for循环,从最后一个非空单元格开始,比较相邻两个单元格是否相同,相同则合并;过程执行后效果如下:
1498291847884690.jpg
逆操作,也就是取消合并,并填充空白单元格Sub unMergeValue()Dim s As StringDim i As LongDim j As LongDim cnt As Integerj = Range("A" & Cells.Rows.Count).End(xlUp).RowFor i = 2 To jWith Cells(i, 1)s = .Valuecnt = .MergeArea.Count.UnMerge.Resize(cnt, 1).Value = sEnd Withi = i + cnt - 1NextEnd Sub代码分析:通过一个for循环,从第二行开始,循环内执行以下操作:取得合并单元格的值S;逐一取得合并单元格合并的单元格个数(MergeArea.Count);合并单元格取消合并(UnMerge);通过resize方法重新取得合并区域,并全部赋值为S; |