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

相关推荐
tlwlmy30 分钟前
python excel图片批量拼接导出
前端·python·excel
开开心心就好2 天前
绿色版PDF多功能工具,支持编辑转换
人工智能·windows·pdf·ocr·excel·语音识别·harmonyos
优选资源分享2 天前
资条生成器 V1.3 - 财务 HR 专属 Excel 工具
excel·实用工具
m0_502724952 天前
vue3在线预览excel表格
javascript·vue.js·excel
Java小王子呀2 天前
JAVA 导出Excel中添加下拉框用POI
java·excel
傻啦嘿哟3 天前
Python 操作 Excel 条件格式指南
开发语言·python·excel
jgyzl3 天前
2026.3.20 用EasyExcel实现excel报表的导入与导出
java·python·excel
Mr.45674 天前
Spring Boot 3 + EasyExcel 3.x 实战:构建高效、可靠的Excel导入导出服务
spring boot·后端·excel
如意机反光镜裸4 天前
excel怎么快速导入oracle
数据库·oracle·excel