Home » excel » excel – VBA. Comparing jagged arrays results in "Type Mismatch"

excel – VBA. Comparing jagged arrays results in "Type Mismatch"

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m having a hard time figuring out what’s wrong with this snippet of code which should be elemental. I was wondering if someone could give me a hand. Any ideas would be very much appreciated, I’m pretty new in VBA.

My code is:

    Dim table() as Variant: table = Array(Array(0,0,0))
    Dim aux() as Variant: aux = Array(0,0,0)
    If table(0) = aux then
    End If

The code doesn’t even execute, Excel throws a mismatch exception in the If line. I have “paraphrased” the code in every way possible and haven’t been successful on getting it to work (of course the code is not as simple as this one, but this one that does nothing doesn’t execute either…)

Thanks in advance for your time,

How to&Answers:

If you want to compare two 1-dimensional arrays for equality as indicated by your provided sample code, then you’ll need to use the Join function, like so:

Sub tst()

    Dim table() As Variant: table = Array(Array(0, 0, 0))
    Dim aux() As Variant:   aux = Array(0, 0, 0)

    If Join(table(0), ",") = Join(aux, ",") Then
        MsgBox "The same"
    Else
        MsgBox "Not the same"
    End If

End Sub

As a note, make sure the Join delimiter being used will not be in any of the elements of either array being tested against. John Coleman brought up a great point that this could give a false positive against an array of (0, "0,0") when using a comma delimiter as shown in the provided answer.