繁体   English   中英

用于检查范围是否包含在另一个范围内的功能

[英]Function to check if a range is contained in another

我期待创建一个函数,检查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的Merged单元格,我希望它算作范围的一部分(即使某些合并的单元格突出)。 为了完成这项工作,我需要写些什么?

考虑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属性来测试它。 假设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作为源应该是安全的,如上面的编辑所示。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM