How to VLOOKUP get #N/A value in VBA?

社会主义新天地 提交于 2019-12-08 09:23:17

问题


I have a data table in Excel, that is same as:

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

I've wrote a VBA function to get value(col B) by key(in col A) Ex: =getValue(A1)

In this example, if I type =getValue(A3), function is throw #VALUE! error. I was debug and see error at VLOOKUP function. Here is my code:

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

How to VLOOKUP get #N/A value in VBA? Thank for your help!


回答1:


You can handle the error as below.

Although I suggest you look consider using a more versatile Find in place of 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


来源:https://stackoverflow.com/questions/11555728/how-to-vlookup-get-n-a-value-in-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!