Excel VBA相交

时间:2015-05-21 19:48:00

标签: excel vba excel-vba intersect

我在网上找到了这个代码,显然它适用于其他人而不是我吗?我不知道哪里错了。我做了一个简单的例子,让我的Range1和Range 2成为excel中的某些单元格,enter image description here

此外,我想知道是否有办法返回交叉路口,如果可以的话。提前谢谢!

Function InRange(Range1 As Range, Range2 As Range) As Boolean
    Set intersectRange = Application.Intersect(Range1, Range2)
    If intersectRange Is Nothing Then
        InRange = False
    Else
        InRange = True
    End If
End Function

2 个答案:

答案 0 :(得分:8)

在我看来,您期望Intersect检查两个范围是否具有相同值的单元格?这是S15和T15中值“a”的重点吗?

如果是这样,那么这就是为什么你没有得到你期望的。相交函数返回两个范围的“重叠”范围,而不管每个范围内的值。

由于这是我在SE上的第一篇文章,我希望这有助于:)

答案 1 :(得分:3)

您的函数没有任何根本错误,但我会将 intersectRange 变量声明为范围。如果你想返回交叉范围,你可以直接从 intersectRange 那里做,并从函数中返回一个变体。

Function InRange(Range1 As Range, Range2 As Range) As Variant
    Dim intersectRange As Range
    Set intersectRange = Application.Intersect(Range1, Range2)
    If intersectRange Is Nothing Then
        InRange = False
    Else
        InRange = intersectRange.Address(0, 0)
    End If
End Function

有关Intersect method的更多信息。