检查范围是否包含在另一个函数

我正在创build一个函数,检查Range2是否包含一个单元格(Range1)。 该function将是:

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

这是为了在Before_DoubleClick事件中检查单元格是否属于一个范围。

预期input/输出的例子( 直接使用地址才能让人更容易想象 ):

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

closures我的头顶,我可以想到一个简单的方法来做到这一点:

 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 

现在是更困难的部分和问题。 如果我select了Range2内的合并单元格,我希望它被视为范围的一部分(即使合并单元格的某些部分伸出)。 我需要写什么来完成这个工作?

考虑A1:B3例子A1:B3是一个合并的单元格(仍然发送地址而不是范围对象作为表示它的一种方式):

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

有没有你不使用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属性来testing。 假设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返回合并范围,如果它是合并区域的一部分。 如果不是,它只是返回单个单元格。 所以当你testing交叉点时,你应该总是使用MergeArea作为源代码,如上所示在编辑中。