Excel VBA - 使用VlookUp内部是错误

时间:2017-03-20 17:58:17

标签: excel-vba vlookup vba excel

我需要通过一系列单元格进行vlookup,并且根据它返回一个值或#N / A,我想对它做一些操作。

我试图将vlookup放在iserror函数中,但这不起作用。

这是我接下来尝试的但是也没有用:

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

你建议我做什么?

由于

2 个答案:

答案 0 :(得分:1)

您的整个代码(您在上面发布的内容)可能看起来像下面的简短版本:

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

答案 1 :(得分:1)

正如我在评论中所说:

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