简体   繁体   English

在Excel VBA中获得#N / A

[英]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 : 如果我在工作表单元格中使用VLOOKUP()而找不到查找值,则VLOOKUP()将返回#N / A

在此处输入图片说明

I want to do the same thing in VBA without putting the formula in a cell. 我想在VBA中做同样的事情而不将公式放在单元格中。 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" 以上返回“错误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 上面引发了1004错误

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 上面也抛出了1004错误

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" . 以上返回“错误2029”

I can get #N/A with: 我可以通过以下方式获得#N / A

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 ?? 有没有一种简单的方法来获取#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: 顺便说一句, Evaluate版出现错误2029的原因是:

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

You could also adjust the formula you pass to Evaluate : 您还可以调整传递给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) (如果第二栏中可能有错误值,请改用IF(ISNA(...)公式)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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