如何VLOOKUP在VBA中获得#N/A值?

Dav*_*vuz 1 error-handling excel vba excel-vba vlookup

我在Excel中有一个数据表,它与:

    A       B
-------------
1. aaa     11
2. bbb     22
3. ccc     #N/A
4. ddd     44
Run Code Online (Sandbox Code Playgroud)

我写了一个VBA函数来按键获取值(col B)(在col A中)Ex: =getValue(A1)

在这个例子中,如果我输入=getValue(A3),则函数抛出#VALUE!错误.我正在调试并在VLOOKUP函数中看到错误.这是我的代码:

Public Function getValue(ByVal key As Variant)

    'get value of the cell at column B which has value 'key' at column A on same row
    column2GetValue = 2
    useClosestMatch = False

    'error here if colum2GetValue contain #N/A
    found = Application.WorksheetFunction.VLookup( _
        key, _
        Worksheets(SHEET_CACHE_NAME).Range("A:B"), _
        column2GetValue, _
        useClosestMatch _
    )

    getValue = found
End Function
Run Code Online (Sandbox Code Playgroud)

如何VLOOKUP在VBA中获得#N/A值? 谢谢您帮忙!

bre*_*tdj 7

您可以按如下方式处理错误.

虽然我建议你考虑使用更多功能Find代替Application.VLOOKUP

Sub TestMe()
Dim vTest As Variant
vTest = Application.VLookup("TesT", Range("A1:B10"), 2, False)
If IsError(vTest) Then
MsgBox "Not found", vbCritical
Else
MsgBox "value is " & vTest
End If
End Sub
Run Code Online (Sandbox Code Playgroud)

  • 删除`WorksheetFunction` (2认同)