简体   繁体   English

在Excel VBA VLookup中为工作表名称使用变量

[英]Using variable for sheet name in excel VBA VLookup

Private Sub UpdateBoxes()
    Dim wsFunc As WorksheetFunction: Set wsFunc = Application.WorksheetFunction
    Dim sheet As String
    If Range("C1") = "some string" Then
        sheet = "SomeSheet"
    End If

    Range("B6").Value = Sheets("Spreadsheet Ctrl").Range("B7") 'Sets title of Box 1 based on Spreadsheet Ctrl
    Range("G6").Value = Sheets("Spreadsheet Ctrl").Range("C7") 'Sets title of Box 2 based on Spreadsheet Ctrl
    Range("B11").Value = Sheets("Spreadsheet Ctrl").Range("D7") 'Sets title of Box 3 based on Spreadsheet Ctrl
    Range("G11").Value = Sheets("Spreadsheet Ctrl").Range("E7") 'Sets title of Box 4 based on Spreadsheet Ctrl
    Range("B16").Value = Sheets("Spreadsheet Ctrl").Range("F7") 'Sets title of Box 5 based on Spreadsheet Ctrl
    Range("G16").Value = Sheets("Spreadsheet Ctrl").Range("G7") 'Sets title of Box 6 based on Spreadsheet Ctrl

    Range("C7").Value = wsFunc.VLookup(B6,'" & sheet & '"!A1:G5,3,)" 'Vlookup for "Current Revision
End Sub

The variable "sheet" will eventually change based on a nested if. 变量“工作表”最终将基于嵌套的if进行更改。 It should then be passed to the last line of code before End Sub . 然后应将其传递到End Sub之前的最后一行代码。 I am getting a compile error that states "Expected: expression", and it highlights the first tick in '" & sheet & '" . 我收到一个指出“ Expected:expression”的编译错误,并突出显示了'" & sheet & '"的第一个刻度。

Something like: 就像是:

Range("C7").Value = wsFunc.VLookup(ActiveSheet.Range("B6"), _
                                   Sheets(sheet).Range("A1:G5"),3,False)

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

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