2015-08-18 73 views
3

我正在創建一個函數,用於檢查Range2中是否包含單元格(Range1)。該功能是:檢查範圍是否包含在另一個函數

Function IsWithin(Range1 as Range, Range2 as Range) as Boolean 

這意味着在Before_DoubleClick事件去檢查單擊單元格屬於範圍。預期輸入/輸出的

例子(直接使用的地址只,使其更容易想象):

IsWithin("A2", "A1:B3") = True 
IsWithin("B1","B1:B2") = True 
IsWithin("A3", "A4:C10") = False 
IsWithin("A3", "A3") = True 

把我的頭,我能想到的一個簡單的方法來做到這一點的頂部:

Function IsWithin(Range1 as Range, Range2 as Range) as Boolean 
    Dim cell2 as range 

    For each cell2 in Range2 
      If cell2.address = Range1.Address then 
       IsWithin = True 
       Exit Function 
      End if 
    Next 

End function 

現在是更難的部分和問題。如果我選擇一個在Range2內部出現的合併單元格,我希望它可以算作範圍的一部分(即使合併單元格的某些部分伸出了)。我需要寫什麼才能完成這項工作?

例考慮A1:B3被合併單元格(仍在發送地址,而不是範圍內的對象,以此來代表它更容易):

IsWithin("A1:B3", "A2:D7") = True 
+0

你會一直在測試一個單元格來檢查它是否在一個更大的範圍內? [包括單個單元是較大合併區域的一部分的情況,這意味着整個合併區域被檢查] –

回答

3

有你爲什麼不使用Intersect()理由嗎?

Dim r As Range 
Set r = Intersect(Range("A2"), Range("A1:B3")) 

If r Is Nothing Then 
    Debug.Print "Not in range" 
ElseIf r.Address = Range("A2").Address Then 
    Debug.Print "Completely within range" 
Else 
    Debug.Print "Partially within range" 
End If 

編輯

由於@Bacon在評論中提到的,這不符合合併的單元格的工作。但是你可以使用MergeArea屬性來測試。假設A1:B1是合併範圍的,這應該工作:

Set r = Intersect(Range("A1").MergeArea, Range("B1:B3")) 

If r Is Nothing Then 
    Debug.Print "Not in range" 
Else 
    Debug.Print "Ranges intersect" 
End If 

MergeArea返回合併範圍,如果它是一個合併區的一部分。如果不是,它只是返回單個單元格。所以你應該是安全的總是使用MergeArea作爲源測試交叉點時,如上圖所示在編輯中。

+0

噢,真好!非常簡單的方法! –

+1

這似乎不適用於合併單元測試 - 如果合併A1:B2並且測試A1是否與B2:C3相交,則顯示「不在範圍內」。但是,從A1開始的合併單元格一直到B2,這意味着合併的單元格部分在範圍內。爲了解決這個問題,我認爲你需要做一個循環,通過在測試區域中找到的所有合併的單元來看看會發生什麼。 –

+1

@ Grade'Eh'Bacon - 你說得對。我添加了一個顯示如何使用'MergeArea'屬性測試合併單元格的編輯。 – Bond

相關問題