Vlookup范围设置不正确

时间:2018-04-01 13:36:07

标签: excel vba excel-vba

以下代码取自VBA vlookup reference in different sheet,但在我尝试根据自己的需求调整时进行了少量更改。简而言之,vlookup代码需要查看工作表1 - A列 - 从单元格 A4 开始直到最后一个输入行,验证是否存在数据位于工作表2 - G列中,如果是,请从第I列中取出旁边的值,转到工作表1 并将其粘贴到其特定值旁边的 B列中。但是,我的方法不起作用。任何帮助都必须得到赞赏!

        Sub vlookupB()
            Dim vlookup As Variant
            Dim lastrow As Long
            Dim ws As Worksheet

        ' i tried to set this in order to take into consideration the last entry from column A.
            Set ws = Sheets("Sheet1")
            lastrow = ws.Cells(Rows.Count, "A").End(xlUp).Row 

            On Error Resume Next

            vlookup = Application.WorksheetFunction.vlookup(ws.Range("A4" & lastrow), _  'start from A4 until its last entry from the column
            Worksheets("Sheet2").Range("G7:I"), 3, False)

            On Error GoTo 0
            If IsEmpty(vlookup) Then

                ' do nothing    
            End If

            Range("B4:B") = vlookup 

        ' paste in column B from sheet1 starting from row B4 until the last entry I have in column A.

        ' so if for e.g. column A has entries until A200, then it should paste the value until B200 - of course, if the value is found in sheet2

    End Sub

1 个答案:

答案 0 :(得分:1)

将公式写入单元格,然后将公式结果恢复为其值。

Sub vlookupB()
    Dim vlookup As Variant
    Dim lastRow As Long, lastRow2 As Long
    Dim ws As Worksheet, ws2 As Worksheet

    Set ws = Sheets("Sheet1")
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    Set ws2 = Sheets("Sheet2")
    lastRow2 = ws2.Cells(ws2.Rows.Count, "G").End(xlUp).Row

    With ws.Range("B4:B" & lastRow)
        .Formula = "=iferror(vlookup(A4, " & ws2.Range("G7:I" & lastRow2).Address(1, 1, external:=True) & ", 3, false), text(,))"
        .Value = .Value
    End With

End Sub