如何在VBA中使用带有可变工作表名称的Vlookup

时间:2015-07-30 08:01:32

标签: excel vba vlookup

我需要在vba中使用vlookup,但工作表名称不断更改,但始终可以引用为ActiveWorkbook.Worksheet(1)和ActiveWorkbook.Worksheet(2)。所以我使用了dim所以所有选择都可以引用ws1和ws2,但当然在vlookup公式中,那种脚本不起作用。希望任何人都可以帮助重写那些vlookup公式行。

它将最后5行与ActiveCell.FormulaR1C1行相关联,我需要为' ws2'! 谢谢你的帮助。

Dim ws1 As Worksheet
Dim ws2 As Worksheet

Set ws1 = ActiveWorkbook.Worksheets(1)
Set ws2 = ActiveWorkbook.Worksheets(2)

ws1.Select
Selection.AutoFilter
Range("G2").Select
ActiveCell.FormulaR1C1 = "Web sales"
Range("H2").Select
ActiveCell.FormulaR1C1 = "Web stock"
Range("I2").Select
ActiveCell.FormulaR1C1 = "Total Sales"
Range("J2").Select
ActiveCell.FormulaR1C1 = "Total Stock"
Range("F2:F71").Select
Selection.Copy
ActiveWindow.SmallScroll Down:=-102
Range("G2:J71").Select
ActiveWindow.SmallScroll Down:=-66
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
    SkipBlanks:=False, Transpose:=False
Columns("H:H").EntireColumn.AutoFit
Range("I5").Select
Application.CutCopyMode = False
Range("D3:D150").Select
ws2.Select
Range("D3:D150").Select
ws1.Select
ActiveWindow.SmallScroll Down:=-66
Range("G3").Select
ActiveCell.FormulaR1C1 = _
    "=VLOOKUP(RC[-3],'ws2'!RC[-3]:R[42]C[-1],3,0)"
ActiveWindow.SmallScroll Down:=-30
ActiveCell.FormulaR1C1 = _
    "=VLOOKUP(RC[-3],ws2!R3C4:R45C6,3,0)"

1 个答案:

答案 0 :(得分:0)

以下是原始代码中的两个示例,说明如何将工作表的名称包含在公式中:

ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-3]," & ws2.Name & "!RC[-3]:R[42]C[-1],3,0)"
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-3]," & ws2.Name & "!R3C4:R45C6,3,0)"