循环 Vlookup VBA

Looping Vlookup VBA

我有两个 excel 文件,我需要通过 VBA 使用 vlookup 函数将数据从一个 excel 文件拉到另一个文件 . 我放置了以下代码并尝试使其动态化

第一段代码如下,

Sub Lookup()


' Identifying first and last row

    Const wsName As String = "TB"
    Const hTitle As String = "India"
    
    Dim wb As Workbook: Set wb = ThisWorkbook
    Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
    
    Dim hCell As Range
    Set hCell = ws.Cells.Find(hTitle, , xlFormulas, xlWhole, xlByRows)
    If hCell Is Nothing Then Exit Sub ' header not found
    
    Dim Col As Long: Col = hCell.Column
    Dim fRow As Long: fRow = hCell.Row
    Dim lRow As Long: lRow = ws.Cells(ws.Rows.Count, Col).End(xlUp).Row
    
    Debug.Print (fRow)
    Debug.Print (lRow)

上面的代码帮助我在 A 列中找到“India”,并确定了它的第一行和最后一行。因为这将是我在下一步中放置 vlookup 的范围。

为了从不同的 excel 文件放置 vlookup,我使用了下面的代码

'Placing vlookup
  
    Dim rw As Long, x As Range
    Dim extwbk As Workbook, twb As Workbook

    Set twb = ThisWorkbook
    Set extwbk = Workbooks.Open("D:\TB_1.xlsx")
        Set x = extwbk.Worksheets("SAP TB").Range("B6:I1048576")

    With twb.Sheets("TBs - Macros")
        For rw = fRow To lRow
            .Cells(rw, 10) = Application.Vlookup(.Cells(fRow, 2).Value2, x, 7, 0)
        Next rw

    End With

    extwbk.Close savechanges:=False
End Sub

上面的代码准确地选择了第一个 Vlookup 值并将其粘贴到整个列范围,我想我在放置循环时犯了错误,因此只有第一个值被复制并粘贴到整个范围。 (如下图所示)

可以看出在公式中正确选择了 155,但是将其粘贴到整列中。

示例数据在下面共享link。 https://drive.google.com/drive/folders/1inrofeT6v9P0ISEcmbswvpxMMCq5TaV0?usp=sharing 将不胜感激!!!

您不需要在该代码区域进行任何迭代。 VLookup 函数能够 return 一个数组,如果它的参数是具有更多行的范围。请替换此部分:

    With twb.Sheets("TBs - Macros")
        For rw = fRow To lRow
            .Cells(rw, 10) = Application.Vlookup(.Cells(fRow, 2).Value2, x, 7, 0)
        Next rw

    End With

这个:

   Dim wsM As Worksheet, rngVLk As Range, rngB As Range

   Set wsM = Twb.Sheets("TBs - Macros")
   Set rngVLk = wsM.Range("J" & fRow, "J" & lRow)
   Set rngB = wsM.Range("B" & fRow, "B" & lRow)
   rngVLk.value = Application.VLookup(rngB, x, 7, False)

为避免遇到此类问题,请在模块顶部写上 Option Explicit。这不会让你 运行 一段代码,如果一个使用的变量以前没有声明并且会 show/select 它。

问题出在循环中:

With twb.Sheets("TBs - Macros")
    For rw = fRow To lRow
        .Cells(rw, 10) = Application.Vlookup(.Cells(fRow, 2).Value2, x, 7, 0)
    Next rw

End With

您正在将变量“rw”从“fRow”移动到“lRow”,但您从未使用过 rw。

我认为你的代码应该是:

With twb.Sheets("TBs - Macros")
    For rw = fRow To lRow
        .Cells(rw, 10) = Application.Vlookup(.Cells(rw, 2).Value2, x, 7, 0)
    Next rw

End With