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

相关推荐
开开心心就好10 小时前
仅168KB的桌面图标自动隐藏工具
windows·计算机视觉·计算机外设·excel·启发式算法·宽度优先·csdn开发云
蒋胜山17 小时前
Excel 练习题(7)
经验分享·excel
蒋胜山19 小时前
Excel 练习题(6)
经验分享·excel
wcy_101121 小时前
QCoder智能生成Excel数据清洗与可视化代码
python·excel
JoshRen2 天前
2026教程:上传Excel,用Gemini 3镜像站多模态一键生成问卷分析图表代码与结论(附国内免费方案)
excel
实战编程3 天前
Temu 插件导出 Excel 图片问题总结(SheetJS / ExcelJS)
excel
Data-Miner3 天前
用DeepSeek V4做表:数以轻舟Agent让做Excel表像聊天一样简单
microsoft·excel
Eiceblue4 天前
使用 C# 将 Excel 转换为 Markdown 表格(含批量转换示例)
开发语言·c#·excel
Java面试题总结4 天前
使用 Python 设置 Excel 数据验证
开发语言·python·excel
追逐梦想永不停4 天前
记录一个好用的excel判断数字格式的公式
前端·chrome·excel