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

相关推荐
VBA63379 小时前
VBA信息获取与处理专题七第二节 网络通信过程的解读
vba
得闲喝茶10 小时前
跨表数据匹配——VLOOKUP、XLOOKUP
大数据·数据库·笔记·信息可视化·数据分析·excel
AI刀刀1 天前
豆包智能体对话导出后,如何构建长期归档与高效检索体系?
android·人工智能·word·excel·ai导出鸭
ZX0X学习中1 天前
一句话让 AI 生成 Excel 多文件合并工具:码道 CLI 实战
人工智能·excel·ai编程·华为云码道
得闲喝茶2 天前
Excel——数据透析表
数据库·经验分享·笔记·其他·信息可视化·excel
小弥儿2 天前
无需安装WPS 和 Office!开源 OfficeCLI,Claude/Copilot 可直接调用,自动生成编辑Word/PPT/Excel
word·powerpoint·excel
Metaphor6922 天前
使用 Python 冻结 Excel 文件中的行、列和单元格
开发语言·python·excel
花 满 楼3 天前
EB引脚配置自动化方案|告别手动繁琐配PIN,Excel+Python批量生成ARXML实现一键配置
python·excel·eb
用户298698530143 天前
Python 实现 Excel 新旧格式互转:告别 Office 依赖的自动化方案
后端·python·excel
未来之窗软件服务4 天前
Excel物业台帐租金合同资产—万象EXCEL应用(28) —东方仙盟
excel·仙盟创梦ide·东方仙盟·万象excel