Сложение строк vba excel

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?

Teamothy's user avatar

Teamothy

1,9903 gold badges15 silver badges24 bronze badges

asked Nov 13, 2009 at 7:31

ilya n.'s user avatar

& 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"

answered Nov 13, 2009 at 7:34

Joey's user avatar

JoeyJoey

341k85 gold badges687 silver badges681 bronze badges

2

The main (very interesting) difference for me is that:
"string" & Null -> "string"
while
"string" + Null -> Null

But that’s probably more useful in database apps like Access.

answered Jun 5, 2018 at 15:48

iDevlop's user avatar

iDevlopiDevlop

24.6k11 gold badges89 silver badges147 bronze badges

There is the concatenate function. For example

=CONCATENATE(E2,"-",F2)

But the & operator always concatenates strings. + often will work, but if there is a number in one of the cells, it won’t work as expected.

Community's user avatar

answered Nov 13, 2009 at 7:38

wallyk's user avatar

wallykwallyk

56.6k16 gold badges85 silver badges147 bronze badges

VBA in Excel stands for Visual Basic for Applications which is Microsoft’s programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. Concatenation means to join two or more data into a single data. There are various ways we can perform concatenation in Excel using built-in functions, operators, etc.

Some helpful links to get more insights about concatenate and using VBA in Excel :

  1. Record Macros in Excel
  2. CONCATENATE in Excel
  3. How to Create a Macro in Excel?

In this article, we are going to see about concatenate operators and how to use VBA to concatenate strings as well as numbers.

Implementation :

In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available. 

The Developer Tab can be enabled easily by a two-step process :

  • Right-click on any of the existing tabs at the top of the Excel window.
  • Now select Customize the Ribbon from the pop-down menu.

  • In the Excel Options Box, check the box Developer to enable it and click on OK.

  • Now, the Developer Tab is visible.

Now, we need to open the Visual Basic Editor. There are two ways :

  • Go to Developer and directly click on the Visual Basic tab.
  • Go to the Insert tab and then click on the Command button. Drag and insert the command button in any cell of the Excel sheet.

Now, double-click on this command button. This will open the Visual Basic Application Editor tab, and we can write the code. The benefit of this command button is that just by clicking on the button we can see the result of concatenation, and also we don’t need to make any extra Macro in Excel to write the code.

Another way is by right-clicking on the command button and then select View Code as shown below :

CONCATENATE Operators:

To concatenate operator mostly used in Excel is “&” for numbers as well as strings. But for strings, we can also use “+” operator to concatenate two or more strings.

The syntax to concatenate using formula is :

cell_number1 & cell_number2 ; without space in between

cell_number1 & " " & cell_number2;  with space in between

cell_number1 & "Any_Symbol" & cell_number2 ; with any symbol in between

cell_number(s) & "string text" ; concatenate cell values and strings

"string_text" & cell_number(s) ; concatenate cell values and strings

CONCATENATE  Two Numbers:

Example 1: Take any two numbers as input and concatenate into a single number.

The code to concatenate two numbers in Excel is :

Private Sub CommandButton1_Click()
'Inserting the number num1 and num2 
Dim num1 As Integer: num1 = 10
Dim num2 As Integer: num2 = 50
'Declare a variable c to concatenate num1 and num2
Dim c As Integer
'Concatenate the numbers
c = num1 & num2
MsgBox ("The result after concatenating two numbers are: " & c)
End Sub

Run the above code in VBA and the output will be shown in the message box.

Output :

The result after concatenating two numbers are: 1050

You can also click on the command button and the same message will be displayed. 

Example 2: Say, now we take two numbers from the cells of the Excel Sheet and store the result back in the Excel sheet. This time we are not going to use the command button.

Step 1: Open the VB editor from the Developer Tab.

Developer  -> Visual Basic -> Tools -> Macros

Step 2: The editor is now ready where we can write the code and syntax for concatenation.

Now write the following code and run it.

Sub Concatenate_Numbers()
'Taking two variables to fetch the two numbers and to store
Dim num1 As Integer
Dim num2 As Integer
'Fetching the numbers from Excel cells num1 from A2 and num2 from B2
num1 = Range("A2").Value
num2 = Range("B2").Value
'Find the concatenate and store in cell number C2
Range("C2").Value = num1 & num2
End Sub

CONCATENATED

Concatenate Two Or more strings:

We can use either “+” operator or “&” operator.

Example 1: Let’s concatenate the strings “Geeks”, “for”, “Geeks”.

Repeat Step 1 as discussed in the previous section to create a new VBA module of name “Concatenate_Strings”

Now write either of the following codes and run it to concatenate two or more strings.

Sub Concatenate_Strings()
'Taking three variables to fetch three strings and to store
Dim str1 As String
Dim str2 As String
Dim str3 As String
'Fetching the strings from Excel cells
str1 = Range("A2").Value
str2 = Range("B2").Value
str3 = Range("C2").Value
'Find the concatenate and store in cell number D2
Range("D2").Value = str1 + str2 + str3
End Sub
Sub Concatenate_Strings()
'Taking three variables to fetch three strings and to store
Dim str1 As String
Dim str2 As String
Dim str3 As String
'Fetching the strings from Excel cells
str1 = Range("A2").Value
str2 = Range("B2").Value
str3 = Range("C2").Value
'Find the concatenate and store in cell number D2
Range("D2").Value = str1 & str2 & str3
End Sub

CONCATENATED

Example 2: Let’s concatenate three strings and add in different lines and display them in a message box this time.

Create a new module and write the code. The keyword used for adding the string in the next line is vbNewLine

The code is :

Sub Concatenate_DifferentLines()
'Taking three variables to store
Dim str1 As String
Dim str2 As String
Dim str3 As String
'Initialize the strings
str1 = "The best platform to learn any programming is"
str2 = "none other than GeeksforGeeks"
str3 = "Join today for best contents"
'Display the concatenated result in a message box
MsgBox (str1 & vbNewLine & str2 & vbNewLine & str3)
End Sub

Example 3: Let’s concatenate two strings with space in between by taking an example of the full name of a person which contains First Name and Last Name.

Create a new module Concatenate_Strings_Space and write the following code :

Sub Concatenate_Strings_Space()
'Taking two variables to fetch two strings and to store
Dim fname As String
Dim lname As String
'Fetching the strings from Excel cells
fname = Range("A2").Value
lname = Range("B2").Value
'Find the concatenate and store in cell number C2
Range("C2").Value = fname & " " & lname
End Sub

Return to VBA Code Examples

In this Article

  • Concatenate Strings
  • Concatenate Cells
    • Concatenate Variables
    • Using the & Operator with Spaces
    • Using the & Operator to Concatenate a Quotation Mark
    • Putting Strings on a New line

We have already gone over an introduction to string functions in our VBA Strings and Substrings Functions tutorial. We are now going to look at how to concatenate text strings.

Concatenate Strings

You can use the & operator in VBA to join text strings.

MsgBox "Merge" & "Text"

vba-concatenate

Concatenate Cells

You can also concatenate cells together. Below, we have the text strings in A1 and B1:

Concatenate Text Strings in VBA

The following code shows you how to join text strings from cell A1 and B1 using the & operator,  in cell C1:

Range("C1").Value = Range("A1").Value & Range("B1").value

The result is:

Using The Concatenate Operator in VBA to join Text Strings

Concatenate Variables

This is the full procedure to concatenate two cells together using string variables.

Sub ConcatenateStrings()

Dim StringOne as String
Dim StringTwo as String

StringOne = Range("A1").Value
StringTwo = Range("B1").Value 

Range("C1").Value = StringOne & StringTwo

End Sub

Using the & Operator with Spaces

When you want to include spaces you use & in conjunction with ” “. The following code shows you how you would include spaces:

Sub ConcatenatingStringsWithSpaces()

Dim StringOne As String
Dim StringTwo As String
Dim StringThree As String

StringOne = "This is"
StringTwo = "the text"
StringThree = StringOne & " " & StringTwo

MsgBox StringThree
End Sub

The MessageBox result is:

Concatenating Text in VBA with Spaces

Using the & Operator to Concatenate a Quotation Mark

Let’s say your text string contains a quotation mark, the following code shows you how to include a quotation mark within a text string:

Sub ConcatenatingAQuotationMark()

Dim StringOne As String
Dim StringTwo As String
Dim StringThree As String

StringOne = "This is the quotation mark"
StringTwo = """"
StringThree = StringOne & " " & StringTwo

MsgBox StringThree

End Sub

The result is:

Using the Concatenate Operator to Concatenate a Quotation Mark

Putting Strings on a New line

Let’s say you have five text strings, you can put each text string on a new line or paragraph, using either the vbNewLine, vbCrLf, vbCr or Chr Function. The following code shows you how to put each text string on a new line:

Sub PuttingEachTextStringOnANewLine()

Dim StringOne As String
Dim StringTwo As String
Dim StringThree As String
Dim StringFour As String
Dim StringFive As String


StringOne = "This is the first string"
StringTwo = "This is the second string"
StringThree = "This is the third string"
StringFour = "This is the fourth string"
StringFive = "This is the fifth string"

MsgBox StringOne & vbNewLine & StringTwo & vbCrLf & StringThree & vbCr & StringFour & Chr(13) & StringFive

End Sub

The result is:

Using vbNewLine to Put Text on its own line in VBA

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

VBA Concatenate Strings

Excel VBA Concatenate Strings

Two or more substrings joining together to form a sentence or new strings are known as concatenation. We have seen concatenation in the worksheet either by using the ampersand operator or the addition operator. Even there is a separate function for concatenation in worksheet functions. But in VBA it is not that similar, in VBA there is no inbuilt function for concatenation of strings also neither can we use the worksheet functions for the same. The only method to concatenate strings in excel VBA is by using the & and + operator.

How to Concatenate Strings in VBA?

Below are the different examples to use the Concatenate Strings in Excel VBA.

You can download this VBA Concatenate Strings Excel Template here – VBA Concatenate Strings Excel Template

VBA Concatenate Strings – Example #1

First, let us begin with the most basic concept of using the & or known as ampersand keystroke used to concatenation in VBA. For this, follow the steps below:

Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.

Insert Module

Step 2: Now we can begin with our subprocedure to show how to concatenate strings in VBA.

Code:

Sub Example1()

End Sub

VBA Concatenate Strings Example1-1

Step 3: Now we need two string variables declared to show how concatenation is done.

Code:

Sub Example1()

Dim Str1, Str2 As String

End Sub

VBA Concatenate Strings Example1-2

Step 4: Let us assign some random values to the variables.

Code:

Sub Example1()

Dim Str1, Str2 As String
Str1 = "Good"
Str2 = "Boy"

End Sub

Random Values Example1-3

Step 5: Now we can use the & or ampersand operator to concatenate both variables.

Code:

Sub Example1()

Dim Str1, Str2 As String
Str1 = "Good"
Str2 = "Boy"
MsgBox Str1 & Str2

End Sub

VBA Concatenate Strings Example1-4

Step 6: Now when we execute the above code we can see the following result.

VBA Concatenate Strings Example1-5

The strings are concatenated together but there is no space available because we didn’t provide it. So this is another lesson that we need to concatenate space too as space is also a character.

VBA Concatenate Strings – Example #2

In the above example we have seen how we concatenated strings also we know that we can use + or addition operator to concatenate strings, can we use concatenation on numbers using the addition operator? Let’s find out. For this, follow the steps below:

Step 1: In the same module let us start another subprocedure as shown below.

Code:

Sub Example2()

End Sub

VBA Concatenate Strings Example2-1

Step 2: Declare two variables as an integer for the integer values.

Code:

Sub Example2()

Dim int1, int2 As Integer

End Sub

Declare Two Variables Example2-2

Step 3: Then assign some values to these integer variables.

Code:

Sub Example2()

Dim int1, int2 As Integer
int1 = 21
int2 = 23

End Sub

VBA Concatenate Strings Example2-3

Step 4: Now let us use the addition operator for the concatenation.

Code:

Sub Example2()

Dim int1, int2 As Integer
int1 = 21
int2 = 23
MsgBox int1 + int2

End Sub

Addition Operator Example2-4

Step 5: If we execute the now we will not get the desired result.

VBA Concatenate Strings Example2-5

Step 6: So, we cannot use the addition operator for concatenation when we use integers, we have to use the ampersand operator and also we need to provide a space.

Code:

Sub Example2()

Dim int1, int2 As Integer
int1 = 21
int2 = 23
MsgBox int1 & " " & int2

End Sub

Ampersand Operator Example2-7

Step 7: Now, let us execute the Code by pressing the F5 key or by clicking on the Play Button.

VBA Concatenate Strings Example2-6

VBA Concatenate Strings – Example #3

So, we cannot use addition operators for integers but we can use them if we treat integer values as string. In this example, we will use integer values as strings. For this, follow the steps below:

Step 1: In the same module let us start with the third example.

Sub Example3()

End Sub

VBA Concatenate Strings Example3-1

Step 2: Now declare two variables as String as shown below.

Code:

Sub Example3()

Dim Str1, Str2 As String

End Sub

VBA Concatenate Strings Example3-2

Step 3: Now, assign integer values to the string variables in double quotation marks.

Code:

Sub Example3()

Dim Str1, Str2 As String
Str1 = "21"
Str2 = "23"

End Sub

VBA Concatenate Strings Example3-3

Step 4: Now using the Msgbox function we will display both using the ampersand operator.

Code:

Sub Example3()

Dim Str1, Str2 As String
Str1 = "21"
Str2 = "23"
MsgBox Str1 & " " & Str2

End Sub

Ampersand Operator Example3-4

Step 5: Run the code by pressing the F5 key or by clicking on the Play Button.

VBA Concatenate Strings Example3-5

VBA Concatenate Strings – Example #4

Now let us note that there may be some circumstances that we need to use the values from worksheets to concatenate. We have two separate values in the sheet as follows. For this, follow the steps below:

Step 1: So in the same module let us start another subprocedure for example 4.

Code:

Sub Example4()

End Sub

VBA Concatenate Strings Example4-1

Step 2: Now declare three variables as Strings.

Code:

Sub Example4()

Dim Str1, Str2, Str3 As String

End Sub

VBA Concatenate Strings Example4-2

Step 3: In the first three variables let us store the values from the worksheets.

Code:

Sub Example4()

Dim Str1, Str2, Str3 As String
Str1 = Range("A1").Value
Str2 = Range("B1").Value

End Sub

First Three Variables Example4-3

Step 4: Now we will use the addition operator for concatenation.

Code:

Sub Example4()

Dim Str1, Str2, Str3 As String
Str1 = Range("A1").Value
Str2 = Range("B1").Value
Str3 = Str1 + Str2

End Sub

Addition Operator Example4-4

Step 5: And we can put the new value in the other cell.

Code:

Sub Example4()

Dim Str1, Str2, Str3 As String
Str1 = Range("A1").Value
Str2 = Range("B1").Value
Str3 = Str1 + Str2
Range("C1").Value = Str3

End Sub

VBA Concatenate Strings Example4-5

Step 6: When we execute the code we can see the result.

VBA Concatenate Strings Example4-6

As explained above there is no inbuilt function for VBA to concatenate strings. Rather than the worksheet function, we use the & (ampersand) and + (addition) operators for it.

Things to Remember About VBA Concatenate Strings

There are few things which we need to remember about concatenate strings in VBA and they are as follows:

1. In the above four examples, we saw that there are two methods to concatenate strings in VBA.
Method 1: By using the ampersand (&) operator.
Method 2: By using the addition (+) operator.
2. We use ampersand and addition operator to concatenate strings in VBA.
3. There is no such function similar to the worksheet concatenate function in VBA.
4. Addition operators used on Integers will add the integers.
5. Space is also a character so between strings Space also needs to be concatenated.

Recommended Articles

This is a guide to VBA Concatenate Strings. Here we discuss How to Concatenate Strings in Excel VBA along with practical examples and downloadable excel template. You can also go through our other related articles to learn more –

  1. VBA SendKeys
  2. VBA On Error Goto
  3. VBA Msgbox Yes/No
  4. VBA SubString

Содержание

  1. Строковые операторы VBA и операторы сравнения
  2. Операторы сравнения
  3. Сравнение строк
  4. Двоичное и текстовое сравнение строк
  5. Конкатенация строк
  6. Оператор конкатенации (&)
  7. Оператор сложения в конкатенации строк
  8. Приоритеты выполнения операций
  9. VBA Concatenate Text Strings Together (& – Ampersand)
  10. Concatenate Strings
  11. Concatenate Cells
  12. Concatenate Variables
  13. Using the & Operator with Spaces
  14. Using the & Operator to Concatenate a Quotation Mark
  15. Putting Strings on a New line
  16. VBA Coding Made Easy
  17. VBA Code Examples Add-in
  18. How can I concatenate strings in VBA?
  19. 3 Answers 3
  20. Linked
  21. Related
  22. Hot Network Questions
  23. Subscribe to RSS
  24. VBA Concatenate
  25. VBA Concatenate Strings
  26. How to Concatenate Strings in VBA?
  27. Common Mistake in Ampersand VBA Concatenation
  28. VBA Concatenate Using JOIN Function
  29. Recommended Articles

Строковые операторы VBA и операторы сравнения

Операторы сравнения

Оператор Синтаксис Описание
= A = B Равенство: Если А равно В, то — True. Иначе — False
Если А меньше В, то — True. Иначе — False
Если А меньше или равно В, то — True. Иначе — False
> A > B Больше: Если А больше В, то — True. Иначе — False
>= A >= B Больше или равно: Если А больше или равно В, то — True. Иначе — False
<> A <> B Не равно: Если А не равно В, то — True. Иначе — False

Обычно операции сравнения используются в операторах организации циклов для принятия какого-либо решения о дальнейшем ходе выполнения операций.

Результатом любой операции сравнения является значение типа Boolean: True, False.

Если оба операнда в выражении сравнения имеют один и тот же тип данных, VBA выполняет простое сравнение для этого типа.

Если оба операнда в выражении сравнения имеют определенные типы и эти типы не являются совместимыми, VBA выдает сообщение об ошибке несовпадения типов.

Если один или оба операнда в выражении сравнения являются переменными типа Variant, VBA пытается преобразовать тип Variant в какой-либо совместимый тип.

Сравнение строк

При сравнении строк операторами отношения, VBA сравнивает каждую строку слева направо посимвольно.

В VBA одна строка равна другой только, когда обе строки содержат точно такие же символы в точно таком же порядке и обе строки имеют одну и ту же длину. Например, строки «абвгд» «абвгд » » абвгд» не равны между собой, т.к. VBA не игнорирует начальные или конечные символы пробела при сравнении строк.

Следует быть внимательным при сравнении строк переменной длины.

Двоичное и текстовое сравнение строк

Для сохранения текста компьютер использует схему, в которой каждый отображаемый символ имеет уникальный номер. Все буквы алфавита имеют свои уникальные номера. Обычно буквы верхнего регистра имеют меньшие номера, чем буквы нижнего регистра. Число, соответствующее определенной букве или символу, называется кодом символа.

При выполнении двоичного сравнения строковой информации VBA использует бинарный эквивалент числа для каждого символа. Такой метод сравнения называется двоичным или бинарным и является методом сравнения по умолчанию.

Т.к. буквы верхнего регистра имеют меньшие двоичные номера, буквы верхнего регистра располагаются в алфавитном порядке перед буквами нижнего регистра. Поэтому при двоичном сравнении строк, строка «АБВ» будем меньше строки «абв».

При текстовом сравнении строк VBA не использует двоичный эквивалент символов, и не «различает» верхнего и нижнего регистра. В текстовом сравнении строка «абв» равна строке «АБВ».

Для выбора метода сравнения строк используется директива Option Compare

Option Compare [Text | Binary]

Данная директива должна находиться в области объявления модуля.

Конкатенация строк

Присоединение одной строки к другой называется конкатенацией строк.

Конкатенацию строк обычно используют для формирования строк из различных источников в процедуре, чтобы создавать сообщение для вывода на экран. В VBA имеется два оператора для конкатенации строк.

Оператор конкатенации (&)

Оператор (&)в VBA используется только для конкатенации строк.

Операнд_1 & Операнд_2 [& Операнд_3..]

Операнд_N — любое допустимое строковое или численное выражение (которое преобразуется в строковое).

Тип данных результата конкатенации строк — String.

Если операнд в выражении конкатенации строк имеет значение Empty или Null, VBA интерпретирует этот операнд как строку нулевой длины (строка не содержащая символов).

Обратите внимание! Символ (&) операции конкатенации обязательно необходимо отделять пробелом от имени переменной, т.к. в противном случае VBA может интерпретировать этот символ как символ определения типа Long.

Оператор сложения в конкатенации строк

Для конкатенации строк можно также использовать оператор (+).

Этот оператор имеет такой же синтаксис и требования, как и оператор (&). Однако следует понимать, что в VBA основное предназначение оператора (+) — это арифметическое сложение. Поэтому, чтобы избежать двусмысленности чтения программного кода, для конкатенации строк настоятельно рекомендуется использовать именно оператор (&).

Приоритеты выполнения операций

Многие из выражений в программной коде являются сложными (составными), т.е. состоят из двух или более выражений.

При вычислении сложных выражений VBA следует следующим правилам:

  • Части выражения, заключенные в круглые скобки, всегда вычисляются в первую очередь;
  • Конкретные операции выполняются в зависимости от иерархии операторов (таблица ниже);
  • При равенстве иерархии операторов, они вычисляются слева направо.
Оператор Комментарии
^ Возведение в степень, высший приоритет
Унарный минус
* / Умножение и деление имеют равные приоритеты
MOD
+ — Сложение и вычитание имеют равные приоритеты
& Конкатенация строк выполняется после арифметических операций перед операциями сравнения и логическими операциями
= ><> Все операции сравнения имеют равные приоритеты и выполняются слева направо. Для группирования операций надо пользоваться круглыми скобками
NOT
AND
OR
XOR
EQV
IMP

В начало страницы

В начало страницы

Источник

VBA Concatenate Text Strings Together (& – Ampersand)

In this Article

We have already gone over an introduction to string functions in our VBA Strings and Substrings Functions tutorial. We are now going to look at how to concatenate text strings.

Concatenate Strings

You can use the & operator in VBA to join text strings.

Concatenate Cells

You can also concatenate cells together. Below, we have the text strings in A1 and B1:

The following code shows you how to join text strings from cell A1 and B1 using the & operator, in cell C1:

Concatenate Variables

This is the full procedure to concatenate two cells together using string variables.

Using the & Operator with Spaces

When you want to include spaces you use & in conjunction with ” “. The following code shows you how you would include spaces:

Using the & Operator to Concatenate a Quotation Mark

Let’s say your text string contains a quotation mark, the following code shows you how to include a quotation mark within a text string:

Putting Strings on a New line

Let’s say you have five text strings, you can put each text string on a new line or paragraph, using either the vbNewLine, vbCrLf, vbCr or Chr Function. The following code shows you how to put each text string on a new line:

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

How can I concatenate strings in 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?

3 Answers 3

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

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:

The main (very interesting) difference for me is that:
«string» & Null -> «string»
while
«string» + Null -> Null

But that’s probably more useful in database apps like Access.

There is the concatenate function. For example But the & operator always concatenates strings. + often will work, but if there is a number in one of the cells, it won’t work as expected.

Linked

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.17.43323

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

VBA Concatenate

Concatenation means joining two values or two strings together, similar to Excel. We use & or also known as an ampersand operator, to concatenate. For example, for two concatenate strings, we use & operators like String 1 and String 2. Now, there is an important thing to remember: while using the & operator, we need to provide spaces, or VBA will consider it long.

VBA Concatenate Strings

VBA concatenates one of those things we used to combine two or more value cell values. So if we say it in simple language, it is combined. It is joining two or more values together to have full value.

But in VBA, we do not have any built-in function to concatenate two or more values together. We do not even get to access the worksheet function class to access the VBA CONCATENATE function as a worksheet function.

Table of contents

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: VBA Concatenate (wallstreetmojo.com)

How to Concatenate Strings in VBA?

Suppose we do not have any built-in function to concatenate values and even do not integrate the worksheet function with VBA. Now the challenge is, how do we combine values?

Even though there are no built-in functions, we can still combine them in VBA using the “ampersand” (&) symbol.

If you follow our posts regularly, we often use the ampersand (&) symbol in our coding.

For example, if you have the first and last names separately, we can combine these two and make them a full name. Then, follow the below steps to write the VBA macro code on our own.

Step 2: Define three variables as String.

Code:

Step 3: Now, assign the variable’s first and last names.

Code:

Step 4: Now, combine these two names to the variable Full_Name using the ampersand variable.

Code:

Step 5: Now, show the value of the variable Full_Name in the message box.

Code:

Now, run the code. We will get the full name in the message box.

The problem with this full name is we have not added a first name and last name separator character space. Therefore, combine space characters while combining the first and last names.

Code:

It will give a proper full name now.

Like this, using the ampersand symbol, we can concatenate values. Now, we will solve the worksheet problem of solving first name and last name together to make it a full name.

Since we need to combine many names, we need to use loops to combine the first and last names. The below code will do the job for you.

Code:

It will combine the first and last names, just like our VBA concatenate function.

Common Mistake in Ampersand VBA Concatenation

If you notice my codes, we have added a space character between values and an ampersand symbol. It is essential because of the nature of VBA programming.

We cannot combine values and ampersand symbols. Otherwise, we will get a “Compile error” like the one below.

VBA Concatenate Using JOIN Function

  • The array is nothing but an array that holds our values—for example, both first name & last name.
  • The delimiter is nothing but what is the separator between each array value, in this case, space character.

The below code will show the example of the same.

Code:

Recommended Articles

This article has been a guide to VBA Concatenate. Here, we learned how to use the Join function’s VBA concatenate function, some practical examples, and a downloadable Excel template. Below are some useful Excel articles related to VBA: –

Источник

Понравилась статья? Поделить с друзьями:
  • Сложение столбцов в таблице excel
  • Сложение столбиком в excel
  • Сложение процента в excel
  • Сложение повторяющихся значений в excel
  • Сложение по цвету ячейки в excel