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

相关推荐
LAM LAB5 天前
【VBA】Excel指定单元格范围内字体设置样式,处理导出课表单元格
excel·vba
在这habit之下6 天前
Keepalived学习总结
excel
Youngchatgpt6 天前
如何在 Excel 中使用 ChatGPT:自动化任务和编写公式
人工智能·chatgpt·自动化·excel
开开心心就好6 天前
安卓开源应用,超时提醒紧急人护独居安全
windows·决策树·计算机视觉·pdf·计算机外设·excel·动态规划
D_C_tyu6 天前
Vue3 + Element Plus | el-table 多级表头表格导出 Excel(含合并单元格、单元格居中)第二版
vue.js·elementui·excel
骆驼爱记录6 天前
WPS页码设置:第X页共Y-1页
自动化·word·excel·wps·新人首发
Cxiaomu7 天前
Python 文件解析: Excel / Word / PDF 的解析、处理、预览与下载
python·word·excel
2501_930707787 天前
如何使用C#代码从 PDF 中提取表格并另存为Excel文件
pdf·excel
pacong7 天前
B生所学EXCEL
人工智能·excel