VBA VLookUp运行时错误

时间:2018-07-16 10:09:07

标签: excel vba excel-vba vlookup

我正在同一工作表上执行循环的vlookup,但出现运行时错误:1004:无法使用以下代码获取WorksheetFunction类的Vlookup属性:

Sub Test()        
    Dim d As Long 
    Dim lastrowx2 As Long 
    lastrowx2 = Worksheets("WS").Cells(Rows.Count, 1).End(xlUp).Row

    For d = 2 To lastrowx2

        Worksheets("WS").Cells(d, 16).Value = _ 'cell where the lookup value will be placed
        Application.WorksheetFunction.VLookup( _ 'vlookup function
        Worksheets("WS").Cells(d, 15).Value, _ 'value to look for
        Worksheets("WS").Range("X:Y"), 2, 0) 'range and column to look    
    Next

End Sub

我在这里做错什么了吗?

2 个答案:

答案 0 :(得分:1)

该代码确实对我有用,尽管我删除了代码中的注释。我唯一能看到的是,如果找不到任何内容,您可能必须使用iferror语句。

Sub Test()

    Dim d As Long
    Dim lastrowx2 As Long, x, sh As Worksheet
    Set sh = Sheets("WS")

    With sh
        lastrowx2 = .Cells(.Rows.Count, 15).End(xlUp).Row

        For d = 2 To lastrowx2
            x = Application.VLookup(.Cells(d, 15).Value, .Range("X:Y"), 2, False)
            If IsError(x) Then x = "Not Found"
            Range("P" & d).Value = x
        Next d
    End With

End Sub

答案 1 :(得分:0)

通常,Application.VLookupWorksheetFunction.VlookUp友好一点。如果未找到后者,则会抛出运行时错误,而第一个会在单元格中写入Excel错误。因此,从一个非常简单的数据开始,然后尝试使其工作是一个好主意。让我们假设你有这个:

enter image description here

该想法是将查找范围“ D:E”中的B列的值写入A列。或在range(“ A1”)上应为600,Range(“ B1”)为500,依此类推。

这是最小的代码:

Sub TestMe()

    Dim curRow As Long
    Dim lastRow As Long

    lastRow = Worksheets(1).Cells(Rows.Count, "B").End(xlUp).Row
    Range("A:A").Clear

    For curRow = 1 To lastRow
        Cells(curRow, "A") = Application.VLookup(Cells(curRow, "B"), Range("D:E"), 2, 0)
    Next

End Sub

运行后的外观如下:

enter image description here

遵循此模型,您可以进一步构建代码。