确定新表对象是否与现有表对象重叠

时间:2018-03-20 11:47:24

标签: excel vba excel-vba

看看下面的代码。当我向工作表中添加一个新的表对象(ListObject)时,我想检查指定的范围是否与另一个现有表重叠。这可以轻松完成,还是需要遍历所有现有表并验证其范围坐标?

Sub TableTest()
    Dim TableObj As ListObject
    Dim WS As Worksheet

    Set WS = ActiveSheet

    ' How can I check if the range isn't overlapping another table before adding it?
    Set TableObj = WS.ListObjects.Add(xlSrcRange, Range("C5:F8"))
End Sub

如果工作表中存在重叠的表格对象,则上面的代码会引发错误(例如,在范围A1:D6)。

1 个答案:

答案 0 :(得分:1)

这样的事情,用Intersect()检查已知范围和新范围:

Sub TableTest()
    Dim TableObj As ListObject
    Dim WS As Worksheet

    Set WS = ActiveSheet
    With WS    
        If Intersect(.Range("C5:F8"), .Range("C1")) Is Nothing Then
            Set TableObj = WS.ListObjects.Add(xlSrcRange, .Range("C5:F8"))
        Else
            Debug.Print "They are intersecting"
        End If    
    End With    
End Sub

如果您想使代码更灵活,没有预定义的表范围,您可以检查所有表的范围与新范围的交叉:

Sub TestMe()

    Dim tableObj As ListObject
    Dim ws As Worksheet
    Dim checkRange As Range

    Set ws = ActiveSheet
    With ws
        For Each tableObj In ws.ListObjects
            If checkRange Is Nothing Then
                Set checkRange = tableObj.Range
            Else
                Set checkRange = Union(checkRange, tableObj.Range)
            End If
        Next tableObj

        If Intersect(.Range("C5:F8"), checkRange) Is Nothing Then
            Set tableObj = ws.ListObjects.Add(xlSrcRange, .Range("C5:F8"))
        Else
            Debug.Print "They are intersecting!"
        End If
    End With

End Sub

在上面的代码中,checkRange是范围,它将所有范围统一起来,并有一个表格。