如何在不使用循环的情况下对动态表执行vlookup和自动填充

时间:2019-05-22 11:38:18

标签: excel vba

我在不同的工作表中有2个表,我必须执行vlookup才能从这两个动态表中获取数据。我已经使用for循环完成了此操作,但是起诉大数据,excel崩溃了。还有其他方法吗?

查找数组中的列将保持不变。但是行将不断变化。

Sheets("HRG").Activate

lastrow = ActiveSheet.UsedRange.Row + ActiveSheet.UsedRange.Rows.Count - 1
lastcolumn = ActiveSheet.UsedRange.Column + 
ActiveSheet.UsedRange.Columns.Count - 1
Set VLRange = ActiveSheet.Range(Cells(2, 1), Cells(lastrow, lastcolumn))

Sheets("HRA").Activate

With ActiveSheet
    lastrowHRA = .Range("A" & .Rows.Count).End(xlUp).Row
End With

For i = 2 To lastrowHRA
    ActiveSheet.Cells(i, lastColHRA + 1) = Application.VLookup(ActiveSheet.Cells(i, 1), VLRange, 11, False)
    ActiveSheet.Cells(i, lastColHRA + 2) = Application.VLookup(ActiveSheet.Cells(i, 1), VLRange, 53, False)
Next i

1 个答案:

答案 0 :(得分:0)

出于所有意图和目的,VLOOKUP只是在该列中查找一个值,然后在该列的另一列中返回该值。

Option Explicit

Sub HRG2HRa()

    Dim i As Long, j As Long, m As Variant
    Dim hrgA As Variant, hrgK As Variant, hrgBA As Variant
    Dim hraA As Variant, hra2C As Variant

    With Worksheets("HRG")

        i = .Cells(.Rows.Count, "A").End(xlUp).Row

        hrgA = .Range(.Cells(2, "A"), .Cells(i, "A")).Value2
        hrgK = .Range(.Cells(2, "K"), .Cells(i, "K")).Value2
        hrgBA = .Range(.Cells(2, "BA"), .Cells(i, "BA")).Value2

    End With

    With Worksheets("HRA")

        i = .Cells(.Rows.Count, "A").End(xlUp).Row
        j = .Cells(1, .Columns.Count).End(xlToLeft).Column

        hraA = .Range(.Cells(2, "A"), .Cells(i, "A")).Value2
        ReDim hra2C(LBound(hraA, 1) To UBound(hraA, 1), 1 To 2)

        For i = LBound(hraA, 1) To UBound(hraA, 1)

            m = Application.Match(hraA(i, 1), hrgA, 0)

            If Not IsError(m) Then

                hra2C(i, 1) = hrgK(m, 1)
                hra2C(i, 2) = hrgBA(m, 1)

            End If

        Next i

        .Cells(2, j + 1).Resize(UBound(hra2C, 1), UBound(hra2C, 2)) = hra2C

    End With

End Sub