人气 3953

[Excel技巧] 合并某一列相邻区域的相同单元格及逆操作 [复制链接]

zzs1808 2017-6-24 16:09:16
如下图,合并第一列相邻区域的相同单元格及逆操作。

1498291834797378.jpg

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

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;
  • 您需要登录后才可以回帖 登录 | 立即注册

    QQ|手机版|精益人 ( 沪ICP备19004111号-1 )|网站地图

    GMT+8, 2024-12-23 00:54 , Processed in 0.254668 second(s), 22 queries .

    Powered by Lean.ren X3.5 Licensed  © 2001-2030 LEAN.REN