Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I concatenate strings in VBA?

Tags:

excel

vba

This question comes from a comment under Range.Formula= in VBA throws a strange error.

I wrote that program by trial-and-error so I naturally tried + to concatenate strings.

But is & more correct than + for concatenating strings?

like image 559
ilya n. Avatar asked Nov 13 '09 07:11

ilya n.


People also ask

Can you concatenate a string with an integer VBA?

VBA Concatenate Strings – Example #2 Step 1: In the same module let us start another subprocedure as shown below. Step 2: Declare two variables as an integer for the integer values. Step 3: Then assign some values to these integer variables. Step 4: Now let us use the addition operator for the concatenation.

How do you concatenate in Excel macro?

Click the top cell in the right column of data that you want to concatenate. For example, if cells A1:A100 and B1:B100 contain data, click cell B1. On the Tools menu, point to Macros, and then click Macro. Select the ConcatColumns macro, and then click Run.

Is the concatenate operator in VBA?

Introduction - VBA Concatenate StringsIn VBA, you concatenate strings into a single string using the & , or ampersand, operator. “Concatenate” is just a fancy way of saying “combine” or “join.” This isn't just a VBA thing. The word “concatenate” is used in almost all programming languages.

How do you append text in VBA?

Starting the program and sub procedure to write VBA Code to Append an existing text file and adding the data. Declaring the strFile_Path variable as String Data Type to store the text file path. Assigning the Existing File path to the variable strFile_Path. Opening the text file for Append with FileNumber as 1.


1 Answers

& is always evaluated in a string context, while + may not concatenate if one of the operands is no string:

"1" + "2" => "12" "1" + 2   => 3 1 + "2"   => 3 "a" + 2   => type mismatch 

This is simply a subtle source of potential bugs and therefore should be avoided. & always means "string concatenation", even if its arguments are non-strings:

"1" & "2" => "12" "1" &  2  => "12"  1  & "2" => "12"  1  &  2  => "12" "a" &  2  => "a2" 
like image 187
Joey Avatar answered Sep 22 '22 13:09

Joey