Search code examples
arraysexcelvbastring-comparison

Compare array entries


I need to compare array entries. I have two arrays with strings like file1.csv. These arrays are filled with almost the same but unsortet strings:

arrayA = {file1.csv, file2.csv, file3.csv ...}
arrayB = {file1.csv, file3.csv, fileABC.csv ...}

My approach was to loop through the arrays and compare the entries like

For i = LBound(arrayA) To UBound(arrayA)
    For j = LBound(arrayB) To UBound(arrayB)
        If arrayA(j) <> arrayB(i) Then
            ' call func
            i = i + 1
        Else
            j = j + 1
        End If

The idea is simple, take one variable j and hold the second i. Loop through both lists and only if one entry is missing, call a function. Here is the problem. My condition does not work for unsorted lists. Because arrayA(2) is equal to arrayB(1) but it triggers the unequal condition instant after one caparision is not equal. But that must first go through the complete array and only then decide whether an entry was missing.


Solution

  • Not sure if you want to loop through arrayA only or through both, but if just A then try:

    Sub Test()
    
    Dim x As Long
    Dim arrayA As Variant: arrayA = Array("file1.csv", "file2.csv", "file3.csv")
    Dim arrayB As Variant: arrayB = Array("file1.csv", "file3.csv", "fileABC.csv")
    
    For x = LBound(arrayA) To UBound(arrayA)
        If IsError(Application.Match(arrayA(x), arrayB, 0)) Then
            Debug.Print arrayA(x) & " Not Found"
        End If
    Next
    
    End Sub
    

    If you want to loop both, then maybe:

    Sub Test()
    
    Dim x As Long, y As Long, z As Long
    Dim arrayA As Variant: arrayA = Array("file1.csv", "file2.csv", "file3.csv")
    Dim arrayB As Variant: arrayB = Array("file1.csv", "file3.csv", "fileABC.csv")
    Dim arrayC As Variant: arrayC = Array(arrayA, arrayB)
    
    For x = 0 To 1
        y = ((x + 1) Mod 2)
        For z = LBound(arrayC(x)) To UBound(arrayC(x))
            If IsError(Application.Match(arrayC(x)(z), arrayC(y), 0)) Then
                Debug.Print arrayC(x)(z) & " Not Found"
            End If
        Next
    Next
    
    End Sub