如何在vba中处理excel合并单元格?

excel工作表中经常会出现合并单元格,当要用vba遍历所有单元格时也经常遇到有合并单元格的情况。

vba为单元格区域对象Range提供了各种处理合并单元格的方法和属性。

Merge 方法 用于合并单元格

如以下代码将合并A1:A3单元格区域

Range("a1:a3").Merge

MergeArea属性用于返回合并单元格区域

如以下代码将判断A1:A10 中哪些单元格位于合并单元格中

Sub QQ1722187970()
    Dim oWK As Worksheet
    Set oWK = Sheet1
    Dim oRng As Range
    Dim oRng1 As Range
    With oWK
        For Each oRng In .Range("a1:A10")
            Set oRng1 = oRng.MergeArea
            If oRng1.Address <> oRng.Address Then
                MsgBox oRng.Address & "位于合并单元格中"
            End If
        Next
    End With
End Sub

MergeCells 属性用于判断某个单元格是否位于合并单元格中

如以下代码将判断A1:A10 中哪些单元格位于合并单元格中

Sub QQ1722187970()
    Dim oWK As Worksheet
    Set oWK = Sheet1
    Dim oRng As Range
    Dim oRng1 As Range
    With oWK
        For Each oRng In .Range("a1:A10")
           MsgBox oRng.MergeCells
        Next
    End With
End Sub

 

       

发表评论