Consider the following piece of VBA code, which generates an array with only two elements, searching for the latter of the two elements. The two commented lines will add a third entry to the array. This produces the output
Error 2042
in the Immediate window. If I change the script to a three element array, and try to Match the second element, I get the proper index in return. If I, however, search for the last element, I get the same error.
Why is this happening?
Working MWE
Sub testArray()
Dim myArray() As Variant
' ReDim myArray(1 To 2)
ReDim myArray(1 To 3)
myArray(1) = "Trondheim"
myArray(2) = "Levanger"
myArray(3) = "Dummy"
Dim Index As Variant
Dim test As Variant
test = "Levanger"
Index = Application.Match(test, myArray)
Debug.Print Index
End Sub
Minimal non-working example
Sub testArray()
Dim myArray() As Variant
' ReDim myArray(1 To 2)
ReDim myArray(1 To 3)
myArray(1) = "Trondheim"
myArray(2) = "Levanger"
myArray(3) = "Dummy"
Dim Index As Variant
Dim test As Variant
'test = "Levanger"
test = "Dummy"
Index = Application.Match(test, myArray)
Debug.Print Index
End Sub
Application.Match)matchis expecting a 2-D array (which is how ranges are represented) and doesn't know how to handle a pointer to a 1-D array. The underlying C/C++ code must be trying to treat it as a 2-D array (just a guess).Match- for exampleApplication.Match(3, Array(2, 3, 4), 0)will work