在 VBA 中连接字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7743823/
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
Concatenating strings in VBA
提问by JMK
I'm maintaining an application written in Microsoft Access with VBA.
我正在维护一个用 VBA 用 Microsoft Access 编写的应用程序。
I'm glancing over my code and have just noticed I have subconsciously been concatenating strings together with the plus (+) symbol instead of the ampersand. It's been a few years since I've coded in VB6. Could this cause any issues?
我正在浏览我的代码,刚刚注意到我已经下意识地将字符串与加号 (+) 符号而不是与号连接在一起。自从我用 VB6 编码以来已经有几年了。这会导致任何问题吗?
Everything seems fine and it will only take a few minutes to fix, I'm just curious as to whether I'm technically doing anything wrong.
一切似乎都很好,只需几分钟即可修复,我只是好奇我在技术上是否做错了什么。
回答by tcarvin
The ampersand is explicitly a string operation, while the plus is overloaded:
&符号是一个明确的字符串操作,而加号是重载的:
Dim num1 As Integer
num1 = RandomNumberBetween(1, 9)
Dim num2 As Integer
num2 = RandomNumberBetween(1, 9)
Dim randomAge As String 'trying to get a random age between 11 and 99
' works
randomDate = "Your age is " & num1 & num2
'broken
randomDate = "Your age is " + num1 + num2
When used with numbers the plus sign will add.
当与数字一起使用时,加号会相加。
回答by phoog
Some examples, from the VBA immediate window (the difference between the third and fourth is particularly vexing):
一些例子,来自VBA的立即窗口(第三个和第四个之间的区别特别令人烦恼):
Print "5" & 6
56
Print 5 & 6
56
Print "5" + 6
11
Print "5" + "6"
56
Print "Five" & 6
Five6
Print "Five" + 6 'Type mismatch
Print "5" & Null
5
Print "5" + Null
Null
回答by Eddy
This can cause issues.
这可能会导致问题。
If you use the plus or ampersand to concatenate string values the results are identical
如果您使用加号或与号连接字符串值,结果是相同的
If you use a plus to concatenate a string with a non string value it will throw an error
如果使用加号将字符串与非字符串值连接起来,则会引发错误
If you use an ampersand sign vba will try to 'stringify' the values before concatenating.
如果您使用与号,vba 将在连接之前尝试“字符串化”这些值。
So string_value + int_value + date_value
will error and string_value & int_value & date_value
works fine
所以string_value + int_value + date_value
会出错并且string_value & int_value & date_value
工作正常