【问题标题】:Combining 2 vlookup formulas in VBA在 VBA 中结合 2 个 vlookup 公式
【发布时间】:2016-05-21 22:24:51
【问题描述】:

我需要一些帮助。

我想从 12 张纸中获取 2 列,C(净关闭数量)和 T(废品产量),并将值与相应的产品代码匹配。我对列 C 和 T 使用 2 个不同的 vlookup 公式,如下所示:

=VLOOKUP($A2:$A226,'01'!$A$2:$T$144,3,FALSE) C 列(净收盘数量) =VLOOKUP($A2:$A226,'01'!$A$2:$T$144,20,FALSE) T 列(废料产量)

我只在第一列尝试过这段代码

Sub Test()
    Dim lastRow As Long

    With Sheets("Summary")
        lastRow = .Cells(.Rows.Count, "D").End(xlUp).Row
        With .Range("C2:C" & lastRow)
            .Formula = "=VLOOKUP($A2,'01'!$A$2:$T$144,3,FALSE)"
            .Value = .Value
        End With
    End With

End Sub

是否可以将两个公式合并到一个 VBA 中?如果可能,如何为每张纸重复这两个公式?我必须通过使用宏来做到这一点,以便它可以自动化。希望有人能给我一些想法,因为我还在学习。非常感谢。

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    您可以使用带有Resize 方法和计步器的循环:

    Sub test()
        Dim lastRow As Long
        Dim j As Byte
    
        j = 1
    
    '// 3(space between columns) x 12(sheets) x 2(lookup columns in each sheet)
    For i = 3 To ((3 * 12) * 2) Step 3
        With Sheets("Summary")
            With .Cells(2, i).Resize(.Cells(.Rows.count, 1).End(xlUp).Row - 1, 1)
                .Formula = "=VLOOKUP($A2,'" & Format$(j, "00") & "'!$A$2:$T$144," & IIf(i Mod 6 = 3, 3, 20) & ",FALSE)"
                .value = .value
            End With
        End With
    
        j = j + 1
    Next
    
    End Sub
    

    请注意,在您的原始代码中,您会从 D 列获得最后一行:

    lastRow = .Cells(.Rows.Count, "D").End(xlUp).Row
    

    由于根据您的屏幕截图,D 列中没有任何内容,因此我使用了 A 列:

    .Cells(.Rows.count, 1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      • 1970-01-01
      相关资源
      最近更新 更多