Vlookup不会循环到下一列

时间:2019-05-24 18:30:29

标签: excel vba for-loop vlookup

我正在尝试让vlookup循环到最后一行和5列。

vlookup转到最后一行,但不会循环到下一列,而是继续到下一行。

我尝试更改行,更新空格并重写下一行以确保正确的间距。

目标是让vlookup继续到最后一行,然后移到下一列5次。

Sub Trial()

    'vlookup to get extra data over
    Workbooks("Final SOR.xlsm").Sheets("Sheet3").Activate

    Dim LastRowLP As Long

    LastRowLP = Sheets("Sheet3").Cells(Rows.Count, 1).End(xlUp).Row

    Dim for_col As Long, i As Long, r As Long, c As Long, colnum As Long

    r = 2: c = 4: colnum = 2

    For for_col = 1 To 5    
        For i = 1 To LastRowLP
            Sheets("Sheet3").Cells(r, c).Value = WorksheetFunction.VLookup(Cells(r, 1).Value, Sheets("UsedData").Range("A:F"), colnum, 0)
            r = r + 1
        Next
        r = 2
        colnum = colnum + 1
        c = c + 1
    Next

End Sub

1 个答案:

答案 0 :(得分:0)

如果您希望 r LastRowLP 处停止,则在循环中使用它,或者在 r 等于 LastRowLP <时退出循环/ em>。

Sub Trial()

    'vlookup to get extra data over
    Workbooks("Final SOR.xlsm").Sheets("Sheet3").Activate

    Dim LastRowLP As Long

    LastRowLP = Sheets("Sheet3").Cells(Rows.Count, 1).End(xlUp).Row

    Dim for_col As Long, i As Long, r As Long, c As Long, colnum As Long

    r = 2: c = 4: colnum = 2

    For for_col = 1 To 5
        For i = 1 To LastRowLP
            Sheets("Sheet3").Cells(r, c).Value = WorksheetFunction.VLookup(Cells(r, 1).Value, Sheets("UsedData").Range("A:F"), colnum, 0)
            r = r + 1
            If r > LastRowLP Then Exit For    'exit the loop
        Next
        r = 2
        colnum = colnum + 1
        c = c + 1
    Next

End Sub

一些数学运算,您可以使用 r c 作为循环中的增量来简化事情。

Sub Trial2()

    'vlookup to get extra data over

    Dim VLUR As Range
    Dim LastRowLP As Long

    With Workbooks("Final SOR.xlsm")

        Set VLUR = .Sheets("UsedData").Range("A:F")

        With Sheets("Sheet3")

            LastRowLP = .Cells(Rows.Count, 1).End(xlUp).Row

            Dim r As Long, c As Long

            For c = 4 To 8
                For r = 2 To LastRowLP
                    .Cells(r, c).Value = Application.VLookup(.Cells(r, 1).Value, VLUR, c - 2, 0)
                Next r
            Next c

        End With

    End With

End Sub