从更大的阵列中删除一个阵列?

时间:2019-04-16 21:05:55

标签: excel vba

我在VBA中有两个数组,我正在尝试获取减去这些数组的第三个子数组,如下所示:

原始数组:

array1=("A","B","C","D")
array2=("B","C")

预期结果:


array1-array2=("A","D")

有没有办法做到这一点?

3 个答案:

答案 0 :(得分:0)

loop the first array and use Application.Match to search the second array.

Load a 3rd array with those items that throw an error from the match:

Sub try()
    Dim array1()
    array1 = Array("A", "B", "C", "D")

    Dim array2()
    array2 = Array("B", "C")

    Dim array3()
    ReDim array3(0)

    Dim i As Long
    For i = LBound(array1) To UBound(array1)            
        If IsError(Application.Match(array1(i), array2, 0)) Then
            array3(UBound(array3)) = array1(i)
            ReDim Preserve array3(UBound(array3) + 1)
        End If
    Next i

    ReDim Preserve array3(UBound(array3) - 1)

    Debug.Print Join(array3, ",")

End Sub

答案 1 :(得分:0)

TBH, I normally find VBA's Filter function next to useless for day-to-day programming requirements and rarely use it but in this case it does seem ideally suited to your purpose if you set the optional third [include/exclude] argument to False.

The following assumes that you want to retain the original values in array1 so a copy of the originals is made in array3 where only exclusion values are retained. I've also used vbTextCompare instead of vbBinaryCompare for a case insensitive filtering operation. Change to vbBinaryCompare for a case sensitive operation.

Option Explicit

Sub arrayDiff()

    Dim i As Long
    Dim array1 As Variant, array2 As Variant, array3 As Variant

    'populate array1 and array2
    array1 = Array("A", "B", "C", "D")
    array2 = Array("B", "C")

    'make a working copy of array1 to process
    array3 = array1

    'loop through the elements in array2 and remove them from array3
    For i = LBound(array2) To UBound(array2)
        array3 = Filter(array3, array2(i), False, vbTextCompare)
    Next i

    'display results in Immediate window
    Debug.Print "array3 = Array(""" & Join(array3, """,""") & """)"

    'alternate result display
    For i = LBound(array3) To UBound(array3)
        Debug.Print array3(i)
    Next i

End Sub

'results from Immediate window
array3 = Array("A","D")
A
D

答案 2 :(得分:0)

You can use a dictionary to create a function that will return an array consisting of array1 - the elements of array2:

Option Explicit
Function arrSubtr(arr1, arr2)
    Dim D As Dictionary
    Dim V

Set D = New Dictionary
    D.CompareMode = TextCompare

For Each V In arr1
    D.Add V, V
Next V

For Each V In arr2
    If D.Exists(V) Then
        D.Remove (V)

'    Uncomment below if you want to add in items in
'    array2 that don't exist in array1
'    Else
'        D.Add V, V
    End If
Next V

arrSubtr = D.Keys

End Function