Excel VBA Intersect

本秂侑毒 提交于 2019-12-11 01:59:00

问题


I found this code online and apparently it works for other people but not me? I don't know where it's wrong. I made a simple example and have my Range1 and Range 2 to be certain cells in excel,

Also, I would like to know if there is a way to return the intersections, if it can. Thanks in advance!

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

回答1:


It seems to me that you are expecting Intersect to check whether the two ranges have cells with the same values? Is that the point from having the value "a" in both S15 and T15?

If so, then this is why you are not getting what you expect. The Intersect function returns a range that is the "overlap" of the two ranges, regardless of the values inside each.

As this is my first post on SE, I hope this helps :)




回答2:


There is nothing fundamentally wrong with your function but I would declare the intersectRange variable as a range. If you wanted to return the intersect range, you can do that directly from intersectRange is not nothing and return a variant from the function.

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

More on the Intersect method.



来源:https://stackoverflow.com/questions/30383042/excel-vba-intersect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!