问题
I have Column A:
+--+--------+
| | A |
+--+--------+
| 1|123456 |
|--+--------+
| 2|Order_No|
|--+--------+
| 3| 7 |
+--+--------+
Now if I enter:
=Match(7,A1:A5,0)
into a cell on the sheet I get
3
As a result. (This is desired)
But when I enter this line:
Dim CurrentShipment As Integer
CurrentShipment = 7
CurrentRow = Application.Match(CurrentShipment, Range("A1:A5"), 0)
CurrentRow gets a value of "Error 2042"
My first instinct was to make sure that the value 7 was in fact in the range, and it was.
My next was maybe the Match function required a string so I tried
Dim CurrentShipment As Integer
CurrentShipment = 7
CurrentRow = Application.Match(Cstr(CurrentShipment), Range("A1:A5"), 0)
to no avail.
回答1:
See the list of VBA Cell Error Values:
Constant Error number Cell error value xlErrDiv0 2007 #DIV/0! xlErrNA 2042 #N/A xlErrName 2029 #NAME? xlErrNull 2000 #NULL! xlErrNum 2036 #NUM! xlErrRef 2023 #REF! xlErrValue 2015 #VALUE!
Try converting the value of CurrentShipment
from an Integer
to a Long
instead of to a String
:
CurrentRow = Application.Match(CLng(CurrentShipment), Range("A1:A5"), 0)
回答2:
As a side note to this and for anyone who gets this error in future, with any function returning a possible error, the variant type works quite well:
Dim vreturn as variant
vreturn = Application.Match(CurrentShipment, Range("A1:A5"), 0) ' this could be any function like a vlookup for example as well
If IsError(vreturn) Then
' handle error
Else
CurrentRow = cint(vreturn)
End If
回答3:
If you look for match function in object browser it returns double so i have declared the variable CurrentRow as double and while it accepts 3 variant parameter. Try below code if it works for you.


Sub sample()
Dim CurrentShipment As Variant
CurrentShipment = 7
Dim CurrentRow As Double
CurrentRow = Application.Match(CurrentShipment, Range("A1:A5"), 0)
End Sub
回答4:
For me it worked fine without type casting anything. I used both:
Application.WorksheetFunction.Match(CurrentShipment, Range("A1:A5"), 0)
and
Application.Match(CurrentShipment, Range("A1:A5"), 0)
Dimensioned CurrentShipment as Integer, Double, Long or Variant, all worked fine...
回答5:
Interestingly, I typed your data into a blank Excel sheet and then ran your original snippet of code. It returned 3, as expected, without having to cast CurrentShipment as String or Long.
Not DIM'ing CurrentRow makes it a Variant by default, but even setting both of them as Integer or CurrentRow as Byte does not throw an error, so using Double as the return type is redundant.
Sub Match()
Dim CurrentShipment As Integer
Dim CurrentRow As Byte '<--- NOTE
CurrentShipment = 7
CurrentRow = Application.Match(CurrentShipment, Range("A1:A5"), 0)
MsgBox CurrentRow
End Sub
来源:https://stackoverflow.com/questions/15526784/why-am-i-getting-error-2042-in-vba-match