The VB languages differentiate between concatenating (“adding”) strings and adding numbers. You’re supposed to use an ampersand (&) to concatenate a string and a plus sign (+) to add numbers. Although VBA will accept a plus sign to concatenate strings it’s frowned on as you can get unexpected results.

JavaScript (like C#) must use the same operator for both operations, the plus sign:

VBA JS
Dim str as String
Dim num as Long
Dim q as Variant
str = "2" & "2"
num = 2 + 2
q = "2" + 2
'Result str: 22
'Result num: 4
'Result q: 4

var str = "2" + "2";
var num = 2 + 2;
var q = 2 + "2";
//Result str: 22
//Result num: 4
//Result q: 22

!!! If you add a numerical string to a number in VBA using the plus sign, VBA performs an addition. What happens if you try to add a string to a number in JavaScript? The number is converted to a string “on-the-fly” and the result is a string concatenation. (See the variable q in the example.)

Leave a Reply