在VBA中组合2个vlookup公式

时间:2016-05-09 14:46:27

标签: excel-vba vba excel

我需要一些帮助。

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

对于C栏(净结算数量),

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

我只针对第一列

尝试了此代码
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?如果可能,如何为每张纸重复这两个公式?我必须通过使用宏来实现这一点,以便它可以自动化。希望有人可以给我一些想法,因为我还在学习。非常感谢你。

1 个答案:

答案 0 :(得分:0)

您可以使用带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)