如何在VBA中连接字符串?

问题描述:

此问题来自VBA中 Range.Formula =下的注释引发一个奇怪的错误.

我通过反复试验编写了该程序,因此我自然尝试使用+连接字符串.

I wrote that program by trial-and-error so I naturally tried + to concatenate strings.

但是,连接字符串时,&+更正确吗?

But is & more correct than + for concatenating strings?

&始终在字符串上下文中求值 ,而如果其中一个操作数不是字符串,则+可能不会连接:

& is always evaluated in a string context, while + may not concatenate if one of the operands is no string:

"1" + "2" => "12"
"1" + 2   => 3
1 + "2"   => 3
"a" + 2   => type mismatch

这只是潜在错误的微妙来源,因此应避免使用. & 总是表示字符串连接",即使其参数为非字符串也是如此:

This is simply a subtle source of potential bugs and therefore should be avoided. & always means "string concatenation", even if its arguments are non-strings:

"1" & "2" => "12"
"1" &  2  => "12"
 1  & "2" => "12"
 1  &  2  => "12"
"a" &  2  => "a2"