Excel VBA - Use VlookUp Inside Is Error

有些话、适合烂在心里 提交于 2020-06-23 14:14:15

问题


I need to do a vlookup through a range of cells, and depending on it returning a value or a #N/A, I want to do some action on it.

I tried to place the vlookup inside the iserror function but that didn't work.

This is what i tried next but is also not working:

Set costCentreMapping = Workbooks.Open(Filename:="C:\mapping.xlsx")
Sheets("Sheet2").Activate
Dim CostCentreRange As Range
Set CostCentreRange = Range("A4:E2967")

    Set test1 = Application.WorksheetFunction.VLookup(appid, CostCentreRange, 2, False)

            If IsError(test1) Then 

                appid.Offset(columnoffset:=15) = "value1"

            End If

What do you recommed me to do?

Thanks


回答1:


As I said in my comment:

Set costCentreMapping = Workbooks.Open(Filename:="C:\mapping.xlsx")

Dim CostCentreRange As Range
Set CostCentreRange = costCentreMapping.Sheets("Sheet2").Range("A4:E2967")

Dim test1 as variant 'the variable must be a variant to accept an error.
    test1 = Application.VLookup(appid, CostCentreRange, 2, False)

            If IsError(test1) Then 

                appid.Offset(columnoffset:=15) = "value1"

            End If



回答2:


Your entire code (that you posted above) could look like the shorter version below:

If IsError(Application.VLookup(appid, CostCentreRange, 2, False)) Then ' <-- not found in VLookup
    appid.Offset(, 15) = "value1"

    If customercountry = "UNITED KINGDOM" Then
        If IsError(Application.VLookup(billService, billableRange, 3, False)) Then
            appid.Offset(, 14) = "value2"
        End If
    End If
End If


来源:https://stackoverflow.com/questions/42910737/excel-vba-use-vlookup-inside-is-error

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