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

相关推荐
刘_sy6 小时前
使用EasyExcel和多线程实现高效数据导出
java·excel·easyexcel·批量导出excel
PowerBI学谦12 小时前
Copilot:Excel中的Python高级分析来了
python·excel·copilot
E-iceblue2 天前
Python 合并 Excel 单元格
python·excel·合并
sszdzq2 天前
Excel 合并列数据
excel
prince_zxill2 天前
Excel中不用复杂公式根据指定X列的数值N复制整行数据N行简单方法
excel
VBAMatrix3 天前
DeepSeek操作Excel,实现图表自动化生成
运维·自动化·excel·wps·deepseek
一醉千秋3 天前
excel中单元格字符串提取数字累加
excel
VB.Net3 天前
19.4.9 数据库方式操作Excel
数据库·c#·excel
真就死难3 天前
CSV格式和普通EXCEL格式文件的区别
linux·excel
朵朵zeng3 天前
Excel文件的读取
python·excel