Home » excel » excel – Show an error when Evaluate Match doesn't find it's criteria

excel – Show an error when Evaluate Match doesn't find it's criteria

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have the following code working without any issues, but I can’t seem to figure out how to make it work with an On Error

row_num2 = Evaluate("MATCH(1,('" & ws1.Name & "'!A:A=""" & variable1 & """)*('" & ws1.Name & "'!B:B=""" & variable2 & """)*('" & ws1.Name & "'!G:G=""" & variable3 & """),0)")

I’ve tired wrapping it with

On Error GoTo ErrMsg
ErrMsg:
    MsgBox "error"
Exit Sub

This works fine if there is an error, but if it is correct then it still shows the “error” MsgBox and Exit’s the Sub

How to&Answers:

The Application.Evaluate method does not throw an exception that you can catch with On Error … instead it returns an error value that can be tested with the IsError function.

If IsError(row_num2) Then
    MsgBox "error in evaluate"
End If

As Mathieu suggested in his comment you can alternatively use
Application.WorksheetFunction.Match
which throws an exception that can be caught with On Error … or Application.Match that returns an error value for IsError.

See WorksheetFunction.Match method.