Excel 宏录制与VBA编程 ——VBA编程技巧篇二 (合并内容相同连续单元格、取消合并单元格并在每个单元格中保留内容)

1、合并内容相同的连续单元格

     如果需要合并如图所示的工作表中B列中部门相同的连续单元格

 

     VBA代码:

cpp 复制代码
Sub Mergerng()
    Dim IntRow As Integer
    Dim i As Integer
    Application.DisplayAlerts = False
    With Sheet1
        IntRow = .Range("A65536").End(xlUp).Row
        For i = IntRow To 2 Step -1
            If .Cells(i, 2).Value = .Cells(i - 1, 2).Value Then
                .Range(.Cells(i - 1, 2), .Cells(i, 2)).Merge
            End If
        Next
    End With
    Application.DisplayAlerts = True
End Sub

 

2、取消合并单元格时在每个单元格中保留内容

     如果需要合并如图所示的工作表中B列中部门相同的连续单元格

 

     VBA代码:

cpp 复制代码
Sub UnMerge()
    Dim StrMer As String
    Dim IntCot As Integer
    Dim i As Integer
    With Sheet1
        For i = 2 To .Range("B65536").End(xlUp).Row
            StrMer = .Cells(i, 2).Value
            IntCot = .Cells(i, 2).MergeArea.Count
            .Cells(i, 2).UnMerge
            .Range(.Cells(i, 2), .Cells(i + IntCot - 1, 2)).Value = StrMer
            i = i + IntCot - 1
        Next
    End With
End Sub

 

关注

笔者 - jxd

相关推荐
用户03321266636710 小时前
使用 Python 轻松移除 Excel 文档中的重复行
python·excel
AI英德西牛仔10 小时前
智谱清言导出word指令失效?PC端深度用户正在用“AI导出鸭”重构内容归档流
人工智能·重构·word·excel·deepseek·ai导出鸭
用户0332126663671 天前
使用 Python 删除 Excel 中的空白行或空白列
python·excel
wuyk5554 天前
Spider-第09讲-三格式落盘CSV-Excel-JSON
爬虫·python·json·excel
黎羽_5 天前
Excel 插图在手机端不显示/错位:完整排查手册
excel·openpyxl·移动端·办公文档
用户298698530146 天前
React 前端实现 Excel 与 CSV 互转:基于 WebAssembly 的浏览器端方案
javascript·react.js·excel
仓库日记7 天前
Excel进销存何时该换?用3项检查判断是否需要软件
经验分享·excel·进销存·开单软件
用户0332126663677 天前
如何使用 Python 将 JSON 转换为 Excel
python·excel
2601_967980118 天前
Python自动化办公:模块、库与样式调整教程
python·excel·自动化办公·openpyxl·样式调整
用户0332126663678 天前
使用 Python 轻松加密或解密 Excel 文档
python·excel