0

谁能解释以下公式的语法在哪里失败?

Selection.FormulaLocal = "=concatenate(vlookup(" & i & ", _
inputs!A5:B43,2,false), " some words")""

如果我想简单地使用 ,该公式可以正常工作vlookup,但是当我尝试添加文本时,我遇到了语法错误。有没有更好的方法来做到这一点而不使用FormulaLocal. 我可以以任何其他方式将 vlookup 与文本结合起来吗?

谢谢!

4

2 回答 2

1

FormulaLocal 属性(和 Formula 属性)需要一个字符串(或字符串文字),它与您从公式栏中键入的公式相同。您正在尝试设置无效的字符串文字:

 "=concatenate(vlookup(" & i & ", inputs!A5:B43,2,false), " some words")""
'<   string literal    >< VBA ><     string literal       ><    VBA  ><string literal>

为了组合两个字符串,您需要使用&,否则它是无效的 VBA 代码:

 "=concatenate(vlookup(" & i & ", inputs!A5:B43,2,false), " & some words & ")""
'<   string literal    >< VBA ><     string literal       ><       VBA     ><string>

The string literal is defined with start and end double-quotes. How do you put a double-quote insde a string literal? In VBA you put two double-quotes:

 "=concatenate(vlookup(" & i & ", inputs!A5:B43,2,false), ""some words"")"
'<   string literal    >< VBA ><           string literal                >
'Resulting formula (i=5): =concatenate(vlookup(5, inputs!A5:B43,2,false), "some words")

Just bear in mind that this is all on the VBA level. The resulting string also has to be a valid formula for Excel. For example, if i is not a number but a word, the formula will end up looking like this:

=concatenate(vlookup(a word, inputs!A5:B43,2,false), "some words")

which is invalid Excel syntax. The solution in this case would be to add double-quotes around i:

"=concatenate(vlookup(""" & i & """, inputs!A5:B43,2,false), ""some words"")"
于 2012-11-30T07:27:11.280 回答
0

尝试添加&instedconcat

="text" & (vlookupformula)

所以你的代码将是,

Selection.FormulaLocal = "= vlookup(" & i & ", _
inputs!A5:B43,2,false) & " some words"

您可以尝试以下方法:

Dim strWords = "some words"
Selection.formula = "= vlookup(" & i & ", _
    inputs!A5:B43,2,false) "
selection.Formula = .Formula & " & """ & strWords & """"
于 2012-11-30T07:20:49.507 回答