繁体   English   中英

在VBA中结合2个vlookup公式

[英]Combining 2 vlookup formulas in VBA

我需要一些帮助。

我想从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列(废品率)$ 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? 如果可能,如何为每张纸重复这两个公式? 我必须通过使用Macro来做到这一点,以便可以将其自动化。 希望有人可以给我一些想法,因为我还在学习。 非常感谢你。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM