excel - 如何在 VBA 中 VLOOKUP 获取#N/A 值?

标签 excel error-handling vlookup vba

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

    A       B
-------------
1. aaa     11
2. bbb     22
3. ccc     #N/A
4. ddd     44

我写了一个 VBA 函数来通过键(在 col A 中)获取值(col B) 例如:=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

如何在VBA中VLOOKUP获取#N/A值? 感谢您的帮助!

最佳答案

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

尽管我建议您考虑使用更通用的 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

关于excel - 如何在 VBA 中 VLOOKUP 获取#N/A 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11555728/

相关文章:

excel - 日期范围内的 VLOOKUP 日期

python - 根据列标题获取Excel列字母 - Python

c++ - 在C++中,异常/错误是否也设置错误号?

excel - 如何将循环中的某些范围复制到正确的方向?

c# - 如何正确处理泛型类中的错误?

php - 如何显示 PHP 错误?

arrays - swift 中的二维数组查找 - 类似于 excel 中的 vlookup

vba - 在 VBA 宏中使用字典的简单 VLOOKUP

按街道名称排列的 VBA 组属性

excel - 在表单前面显示 `ControlTipText`