VLookup in' Do While'环

时间:2015-09-21 20:28:56

标签: excel vba excel-vba vlookup

这' Do While'循环执行,但vlookup有一个小错误。当vlookup结果为" NA"先前存储的vLook值输入到目标(单元格(z,20))。我基本上想说iferror(vlookup(...),"")以便新存储的值为零,然后将vLook值更新为""并输入新的活动单元格。

Sub test3()

Dim text1 As String, text2 As String, text3 As String
Dim vLook As Variant
Dim lookupRange As Range

Set lookupRange = Sheet3.Range("x5:y500")

Z = 5

Do While Sheet3.Cells(Z, 1) <> ""

On Error Resume Next

text1 = Sheet3.Cells(Z, 23)

vLook = Application.WorksheetFunction.VLookup(text1, lookupRange, 2, False)
Sheet3.Cells(Z, 20).Activate
ActiveCell.Formula = vLook


Z = Z + 1
Sheet3.Cells(Z, 24).Select

Loop

End Sub

1 个答案:

答案 0 :(得分:1)

如果删除WorksheetFunction,则如果未找到匹配项,则查找不会引发错误:您可以使用IsError()

测试返回值
Sub test3()

    Dim text1 As String
    Dim vLook As Variant
    Dim lookupRange As Range

    Set lookupRange = Sheet3.Range("x5:y500")

    Z = 5

    Do While Sheet3.Cells(Z, 1) <> ""
        text1 = Sheet3.Cells(Z, 23).Value
        vLook = Application.VLookup(text1, lookupRange, 2, False)
        Sheet3.Cells(Z, 20).Value = IIf(IsError(vLook), "N/A", vLook)
        Z = Z + 1
    Loop

End Sub