简体   繁体   中英

Getting #N/A in Excel VBA

If I use VLOOKUP() in a worksheet cell and the lookup value cannot be found, VLOOKUP() will return #N/A :

在此处输入图片说明

I want to do the same thing in VBA without putting the formula in a cell. What I have tried so far:

Sub FailedLookup()
   Dim v As Variant
   v = Application.VLookup(11, Range("A1:B10"), 2, False)
   MsgBox CStr(v)
End Sub

The above returns "Error 2042"

Sub FailedLookup2()
   Dim v As Variant
   v = WorksheetFunction.VLookup(11, Range("A1:B10"), 2, False)
   MsgBox CStr(v)
End Sub

The above throws a 1004 error

Sub FailedLookup3()
   Dim v As Variant
   v = Application.WorksheetFunction.VLookup(11, Range("A1:B10"), 2, False)
   MsgBox CStr(v)
End Sub

The above also throws a 1004 error

Sub FailedLookup4()
   Dim v As Variant
   v = Evaluate("VLookup(11, Range(""A1:B10""), 2, False)")
   MsgBox CStr(v)
End Sub

The above returns "Error 2029" .

I can get #N/A with:

Sub IsThisReallyNecessary()
   With Range("Z100")
      .Formula = "=VLookup(11,A1:B10, 2, False)"
      MsgBox .Text
   End With
End Sub

But this also uses a cell. Is there a simple way to get #N/A ??

I think you'd need to explicitly check for that error:

   If v = CVErr(xlErrNA) Then MsgBox "#N/A"

BTW, the reason you get Error 2029 with your Evaluate version is that it should be:

v = Evaluate("VLookup(11, A1:B10, 2, False)")

You could also adjust the formula you pass to Evaluate :

   Dim v As Variant
   v = Evaluate("IFERROR(VLookup(11, A1:B10, 2, False),""#N/A"")")
   MsgBox v

(if you might have error values in the second column, use an IF(ISNA(...) formula instead)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM