We help IT Professionals succeed at work.

Compare two arrays

whatemail
whatemail asked
on
Hi,

I am going to have two arrays respectively called arrNew() and arrOld().  These arrays will not be the same number of rows, but will have one column(dimensions) each.

But I am puzzled as to how I should:

1)How can I check if there are cell values in arrNew() that are not in arrOld() quickly and efficiently?

2) Copy arrNew() as arrOld() when I am done.

If you can show code that would oh so good.

Thank you for your help.
Comment
Watch Question

Commented:
Here is simple way to do that:

' Form1 code
Option Explicit

Private Sub Form_Click()
    Dim arrOld() As Variant, arrNew() As Variant
   
    arrOld = Array(1, 2, 5)
    arrNew = Array(1, 2, 4, 6)
   
    'show values in arrNew() that are not in arrOld()
    ShowValues GetNewVals(arrOld, arrNew)
   
    Print "arrOld:"
    ShowValues arrOld
     arrOld = arrNew     ' copy arrNew() as arrOld()
    Print "arrOld:"
    ShowValues arrOld
End Sub

Private Sub ShowValues(ArrOrCollection As Variant)
    Dim e As Variant
    For Each e In ArrOrCollection
        Print e
    Next
End Sub

Private Function GetNewVals(Arr1, Arr2) As Collection
    Dim col1 As Collection, i As Long, tmp As Variant
    On Error Resume Next
   
    Set col1 = New Collection
    Set GetNewVals = New Collection
   
    ' build collection of unique values
    For i = LBound(Arr1) To UBound(Arr1)
        col1.Add Arr1(i), "k" & Arr1(i)
    Next
       
    ' test all values in Arr2
    For i = LBound(Arr2) To UBound(Arr2)
        Err.Clear
        tmp = col1.Item("k" & Arr2(i)) ' if Item does not exist, we'll get error
        If Err Then
            GetNewVals.Add Arr2(i), "k" & Arr2(i)
        End If
    Next
End Function


Note: Any non-A grade will be rejected
You can use the strConv function to get an array.


arr1 = StrConv(strLine1, vbToUnicode)
arr2 = StrConv(strLine2, vbToUnicode)

This gives you a byte array however, so the values are numeric instead of string, but that doesn't
 matter when comparing


for T=0 to Ubound(arr1)  
 If arr1(t) = arr2(t) then      
 Match = Match + 1    
End If    
Msgbox round((match / ubound(arr1) * 100) ,2) & "% of the arrays match"next T


Author

Commented:
Thank you for your help.  I used your code and figured it out.  Thanks for help, great job.

Commented:
Thanks!

Explore More ContentExplore courses, solutions, and other research materials related to this topic.