Как сцепить текст в excel vba

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!

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

 

Kindness

Пользователь

Сообщений: 201
Регистрация: 01.01.1970

Подскажите, пожалуйста, как написать правильно формулу сцепить в VBA  

  Надо, чтобы колонтитул содержал значения нескольких ячеек удаленные друг от друга на определенное количество пробелов, например на 3  

  Worksheets(i).PageSetup.LeftHeader = Worksheets(1).Range(«A1″).Value+»   «+Worksheets(1).Range(«A2»).Value

 

Kindness

Пользователь

Сообщений: 201
Регистрация: 01.01.1970

Спасибо огромное.  

  Сам так пробовал, но не написал пробелы перед и после & — сломал голову что не так!  

  Век живи век учись!!!

 

слэн

Пользователь

Сообщений: 5192
Регистрация: 16.01.2013

[a8] = Join(Array([a7], [b7], [c7]), «oo»)

 

Kindness

Пользователь

Сообщений: 201
Регистрация: 01.01.1970

Спасибо!  

  Возник еще один вопрос…  

  Можно ли сделать левый колонтитул в две строки, то есть чтобы значение ячейки А1 располагалось над значением ячейки В1 в колонтитуле?

 

Kindness

Пользователь

Сообщений: 201
Регистрация: 01.01.1970

Может даже можно вставить в колонтитул целую таблицу?

 

слэн

Пользователь

Сообщений: 5192
Регистрация: 16.01.2013

.LeftHeader = «a1» & Chr(10) & «b1»

 

Kindness

Пользователь

Сообщений: 201
Регистрация: 01.01.1970

Спасибо, СЛЭН!  

  Большое спасибо!

 

Diana

Пользователь

Сообщений: 982
Регистрация: 28.12.2012

{quote}{login=слэн}{date=03.09.2009 03:12}{thema=}{post}[a8] = Join(Array([a7], [b7], [c7]), «oo»){/post}{/quote}

  Здрасьте еще раз…  
а вот если много ячеек нужно сцепить подряд, например:  
A1, B1, C1, D1 и т.д. до AA1. Возможно ли как-то через цикл применить такую вещь?  

  Спасибки всем заранее :)

 

Можно и без цикла :)  

  join(application.transpose(application.transpose([A1:AA1])))

  Еще тема  

http://www.planetaexcel.ru/forum.php/?thread_id=17920

 

Diana

Пользователь

Сообщений: 982
Регистрация: 28.12.2012

Казанский! Чмок тебя в щечку! :) спасибки снова!!! :)

 

слэн

Пользователь

Сообщений: 5192
Регистрация: 16.01.2013

#11

10.11.2010 11:15:20

циклом:  

  for each x in range(..)  
s=s & x  
next  

  или    

  r=range(..)  
for each x in r  
..  

  это и побыстрее чем join будет

Живи и дай жить..

Работа с текстом в коде VBA Excel. Функции, оператор & и другие ключевые слова для работы с текстом. Примеры использования некоторых функций и ключевых слов.

Функции для работы с текстом

Основные функции для работы с текстом в VBA Excel:

Функция Описание
Asc(строка) Возвращает числовой код символа, соответствующий первому символу строки. Например: MsgBox Asc(«/Stop»). Ответ: 47, что соответствует символу «/».
Chr(код символа) Возвращает строковый символ по указанному коду. Например: MsgBox Chr(47). Ответ: «/».
Format(Expression, [FormatExpression], [FirstDayOfWeek], [FirstWeekOfYear]) Преобразует число, дату, время в строку (тип данных Variant (String)), отформатированную в соответствии с инструкциями, включенными в выражение формата. Подробнее…
InStr([начало], строка1, строка2, [сравнение]) Возвращает порядковый номер символа, соответствующий первому вхождению одной строки (строка2) в другую (строка1) с начала строки. Подробнее…
InstrRev(строка1, строка2, [начало, [сравнение]]) Возвращает порядковый номер символа, соответствующий первому вхождению одной строки (строка2) в другую (строка1) с конца строки. Подробнее…
Join(SourceArray,[Delimiter]) Возвращает строку, созданную путем объединения нескольких подстрок из массива. Подробнее…
LCase(строка) Преобразует буквенные символы строки в нижний регистр.
Left(строка, длина) Возвращает левую часть строки с заданным количеством символов. Подробнее…
Len(строка) Возвращает число символов, содержащихся в строке.
LTrim(строка) Возвращает строку без начальных пробелов (слева). Подробнее…
Mid(строка, начало, [длина]) Возвращает часть строки с заданным количеством символов, начиная с указанного символа (по номеру). Подробнее…
Replace(expression, find, replace, [start], [count], [compare]) Возвращает строку, полученную в результате замены одной подстроки в исходном строковом выражении другой подстрокой указанное количество раз. Подробнее…
Right(строка, длина) Возвращает правую часть строки с заданным количеством символов. Подробнее…
RTrim(строка) Возвращает строку без конечных пробелов (справа). Подробнее…
Space(число) Возвращает строку, состоящую из указанного числа пробелов. Подробнее…
Split(Expression,[Delimiter],[Limit],[Compare]) Возвращает одномерный массив подстрок, извлеченных из указанной строки с разделителями. Подробнее…
StrComp(строка1, строка2, [сравнение]) Возвращает числовое значение Variant (Integer), показывающее результат сравнения двух строк. Подробнее…
StrConv(string, conversion) Изменяет регистр символов исходной строки в соответствии с заданным параметром «conversion». Подробнее…
String(число, символ) Возвращает строку, состоящую из указанного числа символов. В выражении «символ» может быть указан кодом символа или строкой, первый символ которой будет использован в качестве параметра «символ». Подробнее…
StrReverse(строка) Возвращает строку с обратным порядком следования знаков по сравнению с исходной строкой. Подробнее…
Trim(строка) Возвращает строку без начальных (слева) и конечных (справа) пробелов. Подробнее…
UCase(строка) Преобразует буквенные символы строки в верхний регистр.
Val(строка) Возвращает символы, распознанные как цифры с начала строки и до первого нецифрового символа, в виде числового значения соответствующего типа. Подробнее…
WorksheetFunction.Trim(строка) Функция рабочего листа, которая удаляет все лишние пробелы (начальные, конечные и внутренние), оставляя внутри строки одиночные пробелы.

В таблице перечислены основные функции VBA Excel для работы с текстом. С полным списком всевозможных функций вы можете ознакомиться на сайте разработчика.

Ключевые слова для работы с текстом

Ключевое слово Описание
& Оператор & объединяет два выражения (результат = выражение1 & выражение2). Если выражение не является строкой, оно преобразуется в Variant (String), и результат возвращает значение Variant (String). Если оба выражения возвращают строку, результат возвращает значение String.
vbCrLf Константа vbCrLf сочетает в себе возврат каретки и перевод строки (Chr(13) + Chr(10)) и переносит последующий текст на новую строку (результат = строка1 & vbCrLf & строка2).
vbNewLine Константа vbNewLine в VBA Excel аналогична константе vbCrLf, также сочетает в себе возврат каретки и перевод строки (Chr(13) + Chr(10)) и переносит текст на новую строку (результат = строка1 & vbNewLine & строка2).

Примеры

Вывод прямых парных кавычек

Прямые парные кавычки в VBA Excel являются спецсимволами и вывести их, заключив в самих себя или в одинарные кавычки (апострофы), невозможно. Для этого подойдет функция Chr:

Sub Primer1()

    ‘Вывод одной прямой парной кавычки

MsgBox Chr(34)

    ‘Отображение текста в прямых кавычках

MsgBox Chr(34) & «Волга» & Chr(34)

    ‘Вывод 10 прямых парных кавычек подряд

MsgBox String(10, Chr(34))

End Sub

Смотрите интересное решение по выводу прямых кавычек с помощью прямых кавычек в первом комментарии.

Отображение слов наоборот

Преобразование слова «налим» в «Милан»:

Sub Primer2()

Dim stroka

    stroka = «налим»

    stroka = StrReverse(stroka) ‘милан

    stroka = StrConv(stroka, 3) ‘Милан

MsgBox stroka

End Sub

или одной строкой:

Sub Primer3()

MsgBox StrConv(StrReverse(«налим»), 3)

End Sub

Преобразование слова «лето» в «отель»:

Sub Primer4()

Dim stroka

    stroka = «лето»

    stroka = StrReverse(stroka) ‘отел

    stroka = stroka & «ь» ‘отель

MsgBox stroka

End Sub

или одной строкой:

Sub Primer5()

MsgBox StrReverse(«лето») & «ь»

End Sub

Печатная машинка

Следующий код VBA Excel в замедленном режиме посимвольно печатает указанную строку на пользовательской форме, имитируя печатную машинку.

Для реализации этого примера понадобится пользовательская форма (UserForm1) с надписью (Label1) и кнопкой (CommandButton1):

Пользовательская форма с элементами управления Label и CommandButton

Код имитации печатной машинки состоит из двух процедур, первая из которых замедляет выполнение второй, создавая паузу перед отображением очередного символа, что и создает эффект печатающей машинки:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

Sub StopSub(Pause As Single)

Dim Start As Single

Start = Timer

    Do While Timer < Start + Pause

       DoEvents

    Loop

End Sub

Private Sub CommandButton1_Click()

Dim stroka As String, i As Byte

stroka = «Печатная машинка!»

Label1.Caption = «»

    For i = 1 To Len(stroka)

        Call StopSub(0.25) ‘пауза в секундах

        ‘следующая строка кода добавляет очередную букву

        Label1.Caption = Label1.Caption & Mid(stroka, i, 1)

    Next

End Sub

Обе процедуры размещаются в модуле формы. Нажатие кнопки CommandButton1 запустит замедленную печать символов в поле надписи, имитируя печатную машинку.


Понравилась статья? Поделить с друзьями:

А вот еще интересные статьи:

  • Как сцепить строчки в excel
  • Как сцепить сразу много ячеек в excel
  • Как сцепить слова в excel с пробелом
  • Как сцепить несколько ячеек в excel через запятую
  • Как сформировать таблицу в word

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии