两个范围数组的交集

时间:2014-05-15 16:31:26

标签: arrays vba range intersection

我目前有两个数组,每个数组都包含范围。你将如何获得这两个数组的交集。换句话说,我想得到一个范围数组,它只包含两个原始数组中包含的范围。我尝试过.Intersect但是在我学习的时候这对数组不起作用。

array1 :(范围(“A1”),范围(“B1”),范围(“C1”)) array2 :(范围(“A1”),范围(“A2”),范围(“A3”))

结果:(范围(“A1”))

1 个答案:

答案 0 :(得分:5)

您可以使用此代码。我们的想法是使用迭代Union将您的数组合并到一个范围内。然后,您可以使用内置的Intersect

Function IntersectArray(array1() As Range, array2() As Range) As Range
    Dim unionRangeArray1 As Range, unionRangeArray2 As Range
    Dim i As Integer

    Dim lbound1 As Integer: lbound1 = LBound(array1)
    Dim lbound2 As Integer: lbound2 = LBound(array2)

    Set unionRangeArray1 = array1(lbound1)
    Set unionRangeArray2 = array2(lbound2)

    For i = lbound1 + 1 To UBound(array1)
        Set unionRangeArray1 = Application.Union(unionRangeArray1, array1(i))
    Next

    For i = lbound2 + 1 To UBound(array2)
        Set unionRangeArray2 = Application.Union(unionRangeArray2, array2(i))
    Next

    Set IntersectArray = Application.Intersect(unionRangeArray1, unionRangeArray2)
End Function