I have this code:
Dim wsFunc As WorksheetFunction: Set wsFunc = Application.WorksheetFunction
Dim ws As Worksheet: Set ws = Sheets("2012")
Dim rngLook As Range: Set rngLook = ws.Range("A:M")
'within a loop
currName = "Example"
cellNum = wsFunc.VLookup(currName, rngLook, 13, False)
VLookup is not expected to always find a result; but when it does not find a result the line errors out before I can even error check it the next line.
The error:
Run-time error '1004': Unable to get the VLookup property of the WorksheetFunction class
It works fine when a result is found. What's a good way to handle errors here?
There is a way to skip the errors inside the code and go on with the loop anyway, hope it helps:
Instead of
WorksheetFunction.Vlookup
, you can useApplication.Vlookup
. If you set aVariant
equal to this it returns Error 2042 if no match is found. You can then test the variant -cellNum
in this case - withIsError
:The
Application
versions of theVLOOKUP
andMATCH
functions allow you to test for errors without raising the error. If you use theWorksheetFunction
version, you need convoluted error handling that re-routes your code to an error handler, returns to the next statement to evaluate, etc. With theApplication
functions, you can avoid that mess.The above could be further simplified using the
IIF
function. This method is not always appropriate (e.g., if you have to do more/different procedure based on theIf/Then
) but in the case of this where you are simply trying to determinie what prompt to display in the MsgBox, it should work:Consider those methods instead of
On Error ...
statements. They are both easier to read and maintain -- few things are more confusing than trying to follow a bunch ofGoTo
andResume
statements.From my limited experience, this happens for two main reasons:
The simple solution here is to use an error handler ending with
Resume Next
If your
lookup_value
is a variable you can enclose it withTRIM()