2014-03-14 71 views
-1

我知道如何命名一系列單元格。如何檢查命名範圍是否在我當前的範圍內?

因此,例如,如果A1到B2被命名爲RangeA,並且我選擇A1到C2,那麼是否有我可以告訴RangeA是否在它內部?

+3

看看'Application.Intersect()' –

+1

@TimWilliams我冒昧地將你的評論擴展爲一個答案... – Floris

+0

@TimWilliams這真棒,我更期待如果我不知道RangeA。像查看選擇中的所有命名範圍。抱歉不清楚。無論如何,這將幫助我。 – elb0w

回答

3

下面是一些代碼,以幫助您在您的方式:

Sub test() 
Dim r1 As Range, r2 As Range, r3 As Range 

Set r1 = Range("A1:A5") 
Set r2 = Range("A3:A6") 
Set r3 = Application.Intersect(r1, r2) 

If Not r3 Is Nothing Then 
    If r3.Cells.Count = r2.Cells.Count Then 
    MsgBox "there is a complete intersection" 
    Else 
    MsgBox "there is some overlap" 
    End If 
Else 
    MsgBox "there is no overlap" 
End If 

End Sub 

應該是不言自明。隨着@TimWilliams的帽子尖端發佈了一條評論。根據您的澄清要求

UPDATE

Sub getIntersectingNames(r As Range) 
    For Each Nm In ActiveWorkbook.Names 
    If Not Application.Intersect(r, Range(Nm)) Is Nothing Then 
     MsgBox Nm.Name & " intersects" 
    End If 
    Next 
End Sub 

Sub test() 
    ' pop up a message box for every range that intersects cell B2: 
    getIntersectingNames [B2] 
End Sub 

Function listIntersectingNames(r As Range) 
    Dim result() As String 
    ReDim result(1 To ActiveWorkbook.Names.Count) 
    Dim matchCount As Integer 

    matchCount = 0 

    For Each Nm In ActiveWorkbook.Names 
    If Not Application.Intersect(r, Range(Nm)) Is Nothing Then 
     matchCount = matchCount + 1 
     result(matchCount) = Nm.Name 
    End If 
    Next 
    ReDim Preserve result(1 To matchCount) 
    listIntersectingNames = result 

End Function 

Sub test2() 
' return an array of names of all ranges that intersect cell B3: 
    ans = listIntersectingNames([B3]) 
    s = "" 
    For Each r In ans 
    s = s & r & vbCrLf 
    Next 
    MsgBox s 
End Sub 

我不知道你是怎麼挺想「迴歸的名單」,所以我給一對夫婦在上面的選項。讓我知道您是否可以將此應用於您的情況,或者您是否需要更多?

+0

謝謝。這非常接近我想要做的事情。我真的很想,如果你能得到你當前選擇的所有命名範圍的列表。不知道其他範圍。 – elb0w

+0

@ elb0w - 根據您的更新請求更新答案。 – Floris

1

進一步擴大了什麼Tim和弗洛裏說,見下圖:

Dim myNamedRange As Range, mySelection As Range, myIntersect As Range 

Set mySelection = Selection '~~> gets your selection 
Set myNamedRange = Range("RangeA") '~~> can be declared or directly pass to Intersect 
Set myIntersect = Intersect(mySelection, myNamedRange) 

    '~~> Then use intersect 
If Not myIntersect Is Nothing Then 
    If myIntersect.Address = myNamedRange.Address Then 
     MsgBox "Your named range is within your selection." 
    Else 
     MsgBox "Your named range is beyond your selection." 
    End If 
Else 
    MsgBox "Your named range is beyond your selection." 
End If 

End Sub 

這是基於其命名範圍RangeA您的實際問題與選擇進行比較。
希望這會有所幫助。

+0

@simoco更正。 :)謝謝simoco! – L42

相關問題