问题
I'm trying to create the equivalent of the =IFERROR(VLOOKUP(),-1) formula in excel VBA where the function would look up text in my data table and return the number in the 5th column if the text is in the table and -1 if it isn't. I've tested the above formula in excel and it gives me the desired result the problem is when I go to code it in VBA I keep getting the #VALUE! error if the text is not in the table. The code produces the desired number if the text is in the table. My code is as follows:
Function CCC(A As Variant)
Dim B As Variant
B = Application.WorksheetFunction.IfError(Application.WorksheetFunction.VLookup(A, Sheets("DAP").Range("$B$4:$X$7"), 5, False), -1)
CCC = B
End Function
With that in mind, is there a way to fix the code so that the IFERROR(VLOOKUP) works and if not what is the best alternative to achieve the same result in VBA?
回答1:
Using Application.WorksheetFunction.VLookup(
will break the code if the value is not found.
Wrap it in vba error control.
Function CCC(A As Range)
Dim B As Variant
B = -1
On Error Resume Next
B = Application.WorksheetFunction.VLookup(A.Value, Sheets("DAP").Range("$B$4:$X$7"), 5, False)
On error goto 0
CCC = B
End Function
Another method is to Late Bind by removing the .WorksheetFormula
and then testing the result.
Function CCC(A As Range)
Dim B As Variant
B = Application.VLookup(A.Value, Sheets("DAP").Range("$B$4:$X$7"), 5, False)
If IsError(B) Then
CCC = -1
Else
CCC = B
End If
End Function
来源:https://stackoverflow.com/questions/45508472/vba-excel-iferror-vlookup-error