Vba excel две строки

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

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

Angrynik

26 / 2 / 0

Регистрация: 04.04.2012

Сообщений: 34

1

Как соединить две строки в одну

26.06.2012, 23:28. Показов 59694. Ответов 6

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Суть такова — есть 2е переменные, нужно склеить их в одну. Например

Visual Basic
1
2
Per1 = "Hello "
Per2 = "World!"

Нужно получить третью переменную «Hello World!»



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

26.06.2012, 23:28

6

mobile

Эксперт MS Access

26777 / 14456 / 3192

Регистрация: 28.04.2012

Сообщений: 15,782

26.06.2012, 23:31

2

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

Visual Basic
1
Per3=Per1 & Per2



1



mc-black

2784 / 716 / 106

Регистрация: 04.02.2011

Сообщений: 1,443

26.06.2012, 23:32

3

Visual Basic
1
Per3 = Per1 & Per2



1



26 / 2 / 0

Регистрация: 04.04.2012

Сообщений: 34

26.06.2012, 23:53

 [ТС]

4

Еще вопрос. Можно ли добавить символ новой строки? Т.е. что бы выводило переменную «Hello World!» как

Hello
World!



0



mobile

Эксперт MS Access

26777 / 14456 / 3192

Регистрация: 28.04.2012

Сообщений: 15,782

26.06.2012, 23:56

5

Цитата
Сообщение от Angrynik
Посмотреть сообщение

Еще вопрос. Можно ли добавить символ новой строки? Т.е. что бы выводило переменную «Hello World!» как

Hello
World!

И это не запрещено.

Visual Basic
1
Per3=Per1 & vbcrlf & Per2



1



Dragokas

Эксперт WindowsАвтор FAQ

17992 / 7618 / 890

Регистрация: 25.12.2011

Сообщений: 11,351

Записей в блоге: 17

27.06.2012, 00:42

6

Лучший ответ Сообщение было отмечено как решение

Решение

Если все переменные типа String, можно пользоваться плюсами:

Visual Basic
1
Per3=Per1 + vbcrlf + Per2



1



4038 / 1423 / 394

Регистрация: 07.08.2013

Сообщений: 3,541

28.09.2016, 22:35

7

Для общего развития
В VBA при конкатенации строк через «+» есть особенности
«строка» & Null Результат «Строка»
«строка» + Null Результат Null
более того «+» при объединении строк ругается на числовые данные и данные дата/время и их нужно конвертировать с помощью CStr или Str



1



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

28.09.2016, 22:35

7

Содержание

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

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

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

Источник

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 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.

Источник

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.

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

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.

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

Code:

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

Code:

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

Code:

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

Code:

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

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:

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

Code:

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

Code:

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

Code:

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

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:

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

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.

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

Code:

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

Code:

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

Code:

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

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:

Step 2: Now declare three variables as Strings.

Code:

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

Code:

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

Code:

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

Code:

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

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 –

Источник

Понравилась статья? Поделить с друзьями:
  • Vba excel дата по формату
  • Vba excel дата изменения ячейки
  • Vba excel данные с одного столбца в столбец
  • Vba excel данные не открывая
  • Vba excel группировка свернуть