【VBA案例017】合并单元格

大家好!

合并单元格是经常遇到的操作,在WPS中,提供了非常好用的快捷按钮。遗憾的是Excel里并没有这个一键合并单元格的功能。

今天分享用VBA合并单元格的两个最常用的方法,如果你是WPS用户,虽然不需要代码,但是编程的思路,还是有参考价值的。

以下是VBA代码。详细解析请看文末的视频。

方法一:#

Sub union并集函数()

    Dim i
    Dim rng As Range

    Set rng = [a2]

    Application.DisplayAlerts = False
    For i = 2 To 20
        If Range("a" & i + 1) = Range("a" & i) Then
            Set rng = Union(rng, Range("a" & i + 1))
        Else
            rng.Merge
            Set rng = Range("a" & i + 1)
        End If
    Next i
    Application.DisplayAlerts = True

End Sub

方法二:#

Sub 循环数组()

    Dim i, j, ar
    Dim start_row, end_row

    ar = [a1:a20]
    start_row = 2

    Application.DisplayAlerts = False
    For i = 2 To UBound(ar)
        For j = i + 1 To UBound(ar)
            If ar(j, 1) = ar(i, 1) Then
                end_row = j
            Else
                end_row = j - 1
                Exit For
            End If
        Next j
        Range("a" & start_row & ":a" & end_row).Merge
        start_row = j
        i = start_row - 1
    Next i
    Application.DisplayAlerts = True

End Sub

原始链接

目录: