Vba excel соединить строки

Angrynik

26 / 2 / 0

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

Сообщений: 34

1

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

26.06.2012, 23:28. Показов 59697. Ответов 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

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

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

Home / VBA / VBA Concatenate

To concatenate two strings using a VBA code, you need to use the ampersand. You can use an ampersand in between two strings to combine them and then assign that new value to a cell, variable, or message box. In the same way, you can concatenate more than two values as well.

Further, we will see a simple example to understand it.

Steps to use VBA to Concatenate

  1. First, enter the first string using double quotation marks.
  2. After that, type an ampersand.
  3. Next, enter the second text using double quotation marks.
  4. In the end, assign that value to a cell, or variable, or use a message box to see it.
string using double quotation
Sub vba_concatenate()
Range("A1") = "Puneet " & "Gogia"
End Sub

You can also use a delimiter within two strings by simply adding a third ampersand. Consider the following code.

Range("A1") = "Puneet " & "-" & "Gogia"

In the above code, you have used a delimiter within two strings and joined them by simply using ampersands. So basically, whenever you need to join anything you have to use an ampersand within.

Concatenate using Variables

You can also store values in variables and then concatenate values from those two variables. Consider the following code.

concatenate using variables

In the above code, you have variables that are declared as variables and then you have assigned values to those variables. And in the end, we used an ampersand to combine all three variables and then assigned the result to cell A1.

Concatenate a Range using VBA

You can also concatenate values from a range of cells using a VBA. Consider the following macro.

Sub vba_concatenate()

Dim rng As Range
Dim i As String
Dim SourceRange As Range

Set SourceRange = Range("A1:A10")

For Each rng In SourceRange
i = i & rng & " "
Next rng
Range("B1").Value = Trim(i)

End Sub

In the above code, you have used the FOR NEXT (For Loops) to loop through the range that you want to concatenate.

So it goes to each cell of the range (A1:A10) stores that value in the I variable, and uses an ampersand to concatenate a value with each iteration. In the end, set the combined string to range B1.

And the following code concatenates the values from the selected range. All you need to do is to select a range and then run the code.

Dim rng As Range
Dim i As String

For Each rng In Selection
i = i & rng & " "
Next rng

Range("B1").Value = Trim(i)

Concatenate Entire Column or a Row

If you want to concatenate an entire column or a row, in that case, it’s better not to use the loop method. You can use the worksheet function “TextJoin” which can join an entire row or a column (consider the following code).

'join values from column A.
Dim myRange As Range
Dim myString As String
Range("B1") = WorksheetFunction.TextJoin(" ", True, Range("A:A"))

'join values from row 1.
Dim myRange As Range
Dim myString As String
Range("B1") = WorksheetFunction.TextJoin(" ", True, Range("1:1"))

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