VBA Vlookup值与第一行相同

时间:2018-03-23 03:17:15

标签: excel vba excel-vba for-loop vlookup

我尝试在for循环条件下使用vlookup()函数,但该值仅遵循第一行值。这是我的代码。对不起,代码很乱;我还在学习VBA。

Sub vlookup_Click()
Application.ScreenUpdating = False
Dim result As String
Dim i As Long
Dim iLast As Long
Dim result1 As String
Dim sheet As Worksheet
Dim sheet1 As Worksheet
Dim WrkSht As String
WrkSht = "Sheet1"
iLast = ActiveWorkbook.Worksheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
Set sheet = ActiveWorkbook.Sheets("Sheet1")
Set sheet1 = ActiveWorkbook.Sheets("InventoryReport")


For i = 10 To iLast
    result = Application.WorksheetFunction.VLookup(sheet.Range("$B$10"), _ 
            sheet1.Range("$B$10:$Q$48"), 16, False)
    Sheets(WrkSht).Cells(i, 9).Value = result
Next i

End Sub

下图显示了结果。有什么想法可以解决这个问题吗?

预期和当前结果:
Expected and Current Result

2 个答案:

答案 0 :(得分:0)

因此,我们考虑转储VLOOKUP()选项。我们正在使用VBA,因此在查找范围时我们拥有更多的力量。

我认为我们应该在这里使用range.Find()方法。设置此对象,使用Row()属性匹配该范围内的Q列,并将其返回到ws1中的I列。

试试这个

Sub vlookup_Click()

    Application.ScreenUpdating = False

    Dim i As Long
    Dim iLast As Long
    Dim ws1 As Worksheet, ws2 As Worksheet
    Dim findRng As Range

    Set ws1 = ThisWorkbook.Sheets("Sheet1")
    Set ws2 = ThisWorkbook.Sheets("InventoryReport")

    'Changed ActiveWorksheet to ws1 for your iLast
    iLast = ws1.Range("A" & Rows.Count).End(xlUp).Row

    For i = 10 To iLast

        Set findRng = ws2.Range("B:B").Find(ws1.Cells(i, "B"), , xlValues, xlWhole)

        If Not findRng Is Nothing Then
            ws1.Cells(i, "I") = ws2.Cells(findRng.Row, "Q")
        Else
            ws1.Cells(i, "I") = 0
        End If

        Set findRng = Nothing

    Next i

    Application.ScreenUpdating = True

End Sub

答案 1 :(得分:0)

我看到你使用excel工作表函数,但使用formulaR1C1的形式会更好。并记录宏将使您无需计算公式的行#。 怎么做: 您可以通过点击标签“开发人员”来录制此操作,以便在您的Excel中获取该代码 excel /“record Macro”然后在单元格中输入公式,然后“停止录制”,然后按Alt + F11进入 访问vlookup公式的代码:

ActiveCell.FormulaR1C1 = "=VLOOKUP(R10C2,R[3]C[-1]:R[41]C[11],16,0)"