Automating data reconciliation in Microsoft Excel using Visual Basic for Applications (VBA) often involves executing lookup queries via Application.WorksheetFunction.VLookup. When the target lookup value does not exist in the specified range or table column, VBA halts execution and throws: Run-time error ‘1004’: Unable to get the VLookup property of the WorksheetFunction class. Unlike regular worksheet cells that simply display #N/A, calling WorksheetFunction raises a fatal runtime exception if an exact match is missing.
Replace WorksheetFunction with Application.VLookup
The standard architectural fix in VBA is to omit WorksheetFunction and assign the lookup result directly to a Variant data type, which captures lookup errors gracefully:
Sub SafeVLookupExample()
Dim lookupVal As String
Dim lookupRange As Range
Dim result As Variant
lookupVal = Range("A2").Value
Set lookupRange = Worksheets("LookupTable").Range("A2:D500")
' Call Application.VLookup directly instead of WorksheetFunction
result = Application.VLookup(lookupVal, lookupRange, 2, False)
' Evaluate whether the function returned an error
If IsError(result) Then
Range("B2").Value = "Not Found"
Else
Range("B2").Value = result
End If
End Sub
Implement On Error Resume Next Block Handling
If you prefer retaining the WorksheetFunction object syntax across legacy codebases, wrap the execution in structured error trapping:
- Precede the lookup statement with error suppression:
On Error Resume Next result = Application.WorksheetFunction.VLookup(lookupVal, lookupRange, 2, False) If Err.Number <> 0 Then result = "Match Missing" Err.Clear End If On Error GoTo 0 - Reset error handling immediately with
On Error GoTo 0to ensure unexpected failures elsewhere in your subroutine are properly surfaced.
Verify Leading Spaces and Data Type Alignment
Ensure that numerical identifiers stored as text in the search column match the exact data type passed into the lookup variable, as type mismatches between string and integer representations trigger lookup misses.