Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting Error 2042 in VBA Match?

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.

like image 375
user2140261 Avatar asked Mar 20 '13 14:03

user2140261


People also ask

How do I fix a VBA error in Excel?

To do this, click on 'Tools' and then click on 'Options'. In the options dialog box, make sure that the 'Auto Syntax Check' option is enabled. If the 'Auto Syntax Check' option is disabled, VBA will still highlight the line with the syntax error in red, but it will not show the error dialog box.

How do I fix compile errors in VBA?

I have resolved same error by following these 4 steps : Open Excel file which is having issue, press Alt + F11 go into its Visual Basic Editor. From the Tools menu select References ( Note, if references option is disabled in tools menu try closing and reopening file and enable Macro before proceeding next steps)

How do I bypass VBA error?

If we want to ignore the error message only for a specific code set, close the On Error Resume Next statement by adding the “On Error GoTo 0” statement.


2 Answers

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
like image 132
KDT Avatar answered Sep 23 '22 03:09

KDT


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)
like image 36
Vincent MAURY Avatar answered Sep 22 '22 03:09

Vincent MAURY