Concatenating strings in VBA

喜欢而已 提交于 2019-12-01 16:58:42

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.

Some examples, from the VBA immediate window (the difference between the third and fourth is particularly vexing):

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

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.

So string_value + int_value + date_value will error and string_value & int_value & date_value works fine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!