range.formula不接受字符串

时间:2017-07-10 18:53:18

标签: excel vba excel-vba

我试图将vlookup公式提供到一个范围内,但它似乎并没有接受字符串。我在这里缺少什么?

Dim inBudget As Range, lookupValue As String, result As String, inForm As String
Set inBudget = Range("C8")
Set dataSheet = ActiveWorkbook.Sheets("Data")
Set reportSheet = ActiveWorkbook.Sheets("Report")
For j = 1 To 3
'' change 3 to years using current data -2016 +1
    For i = 1 To 12
    lookupValue = 2015 + j & dptNum & "BudgetRCPT$"
    inForm = "=vlookup(" & lookupValue & ",Data!A2:AK" & dataLastRow & "," & CStr(11 + i) & ")"
    Debug.Print inForm
    inBudget.Formula = inForm
    Set inBudget = inBudget.Offset(0, 1)
    Next i
Next j

如何计算dataLastRow

dataLastRow = LastRow("A")

Function LastRow(colName As String) As Long 'Find the last used row in a Column: column A in this example
    With ActiveSheet
        LastRow = .Range(colName & CStr(.Rows.Count)).End(xlUp).Row
    End With End Function

1 个答案:

答案 0 :(得分:0)

想出我的问题是没有关于vlookup值的引号。

    For j = 1 To 3
'' change 3 to years using current data -2016 +1
    For i = 1 To 12
    lookupValue = Chr(34) & 2015 + j & dptNum & "BudgetRCPT$" & Chr(34)
    inForm = "=VLOOKUP(" & lookupValue & ",Data!A2:AK" & dataLastRow & "," & CStr(11 + i) & ")"
    Debug.Print inForm
    inBudget.Formula = inForm
    Set inBudget = inBudget.Offset(0, 1)
    Next i
Next j

vlookup的第一个参数需要括在括号中。我添加了Chr(34)来解决这个问题。