Why doesn't isError( ) work with a vlookup statement in excel VBA

笑着哭i 提交于 2019-12-11 01:19:15

问题


I'm using excel 2007 and have created a UDF that includes three vlookup() statements. The function is supposed to return the sum of all three vlookup statments. In the majority of cases, only two the vlookup() statements will return a valid value the third statement will result in an NA because the lookup value is not included in the lookup range.

I have tried to trap the error and return a zero by using:

  1. Application.WorksheetFunction.iferror(vlookup(...) ,0)

  2. A conditional that uses If iserror(vlookup()) then ...

but I can't seem to get either approach to work. If I comment out the vlookup that I know is creating the error everything works as expected.

Does anyone know why iserror(0 and iserror() don't seem to be working or perhaps an alternative approach that will work.

Update:

Here are the three vlookup function:

product2 = Application.WorksheetFunction.IfError(Application.WorksheetFunction.VLookup(productA, lookuprng, offset, False), 0)

product3 = Application.WorksheetFunction.IfError(Application.WorksheetFunction.VLookup(productB, lookuprng, offset, False), 0)

product4 = Application.WorksheetFunction.IfError(Application.WorksheetFunction.VLookup(productC, lookuprng, offset, False), 0)

回答1:


You can trap the error with the following:

Sub HandleVlookupErrors()
    Dim result As Variant

    result = Application.VLookup(productA, lookuprng, offset, False)
    If IsError(result) Then result = 0

End Sub

For a full explanation, please see Error Handling Within Worksheet Functions.




回答2:


You may consider to write a vlookup function with error handling lines:

Public Function v_lookup(lookup_value As String, table_array As Range, col_index_num As Integer, range_lookup As Boolean) As String

Dim result As Variant
result = Application.VLookup(lookup_value, table_array, col_index_num, range_lookup)

If IsError(result) Then result = ""
v_lookup = result

End Function



回答3:


Dim Res as Variant
Res = Application.WorksheetFunction.VLookup(Vndr, Range("A:a"), 1, False) 'Where Vndr is some unknown
If Res = Vndr then 
    do xyz
Else
    do 123
endif


来源:https://stackoverflow.com/questions/17177709/why-doesnt-iserror-work-with-a-vlookup-statement-in-excel-vba

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