9

I'm maintaining an application written in Microsoft Access with VBA.

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?

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.

3 Answers 3

13

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It gets even more chancy when you have a null with plus.
Good point, appending a string to a null with the ampersand safely results in a value that is just that string
4

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

Comments

1

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

2 Comments

Your example is (partly) correct, but the sentences above it are backwards. If you use ampersand to concatenate a string with a non-string value, the non-string value is converted to a string and concatenated. If you use plus, you get an error, unless the string value is numeric, in which case it is converted to a number, and the values are added. Also, if you use plus and one of the operands is null, the result is null; this doesn't happen with amepersand.
Thanks I fixed the swapped sentences to eliminate any confusion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.