简体   繁体   English

Excel VBA在vlookup公式中使用单元格值

[英]Excel VBA Using cell value in vlookup formula

I am trying to create a vlookup to a worksheet that has the same name as the cell value in my active sheet. 我正在尝试创建一个与工作表中的单元格名称同名的工作表的vlookup。

I created the following thinking I could use the 'str' in my vlookup formula but, I get 'Run-time error '1004': Application-defined or object-defined error' 我产生以下想法,认为可以在vlookup公式中使用“ str”,但是出现“运行时错误” 1004”:应用程序定义的错误或对象定义的错误”

Sub copy()

    Dim LastRow As Long
    Dim str As String

    str = Cells(1, 5).Value

    With Sheets("Overview")
        LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row

        With .Range("E2:E" & LastRow)
            .Formula = "=VLOOKUP(B2, & str &!B:F,5,FALSE)"
        End With

    End With

End Sub

Can anyone see what I am doing wrong? 谁能看到我在做什么错?

You've defined str in VBA but referred to it in the formula without closing off the quotation marks, try this: 您已经在VBA中定义了str ,但是在公式中引用了它而不关闭了引号,请尝试以下操作:

Sub copy()

Dim LastRow As Long
Dim str As String

str = Cells(1, 5).Value

With Sheets("Overview")
    LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row

    With .Range("E2:E" & LastRow)
        .Formula = "=VLOOKUP(B2," & str & "!B:F,5,FALSE)"
    End With

End With

End Sub

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

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