Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating strings in VBA

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.

like image 916
JMK Avatar asked Oct 12 '11 17:10

JMK


2 Answers

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.

like image 51
tcarvin Avatar answered Sep 17 '22 20:09

tcarvin


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
like image 28
phoog Avatar answered Sep 19 '22 20:09

phoog