如何在 VBA 中连接字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1727699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:08:05  来源:igfitidea点击:

How can I concatenate strings in VBA?

excelvba

提问by ilya n.

This question comes from a comment under Range.Formula= in VBA throws a strange error.

这个问题来自Range.Formula= in VBA下的一条评论引发了一个奇怪的错误

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

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

But is &more correct than +for concatenating strings?

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

回答by Joey

&is alwaysevaluated 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. &alwaysmeans "string concatenation", even if its arguments are non-strings:

这只是潜在错误的微妙来源,因此应该避免。&始终表示“字符串连接”,即使其参数是非字符串:

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

回答by Patrick Honorez

The main (very interesting) difference for me is that:
"string" & Null-> "string"
while
"string" + Null-> Null

对我来说主要的(非常有趣的)区别在于:
"string" & Null-> "string"
while
"string" + Null->Null

But that's probably more useful in database apps like Access.

但这在 Access 等数据库应用程序中可能更有用。

回答by wallyk

There is the concatenate function. For example

有连接函数。 例如

=CONCATENATE(E2,"-",F2)
但是 & 运算符总是连接字符串。+ 通常会起作用,但如果其中一个单元格中有一个数字,它将无法按预期工作。