Склеить значения excel vba

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

Объединение диапазона ячеек в одну или построчно с помощью кода VBA Excel. Метод Range.Merge и свойство MergeCells. Отмена объединения ячеек. Примеры.

Метод Range.Merge

Метод Merge объекта Range объединяет ячейки заданного диапазона в одну или построчно из кода VBA Excel.

Синтаксис метода:

  1. Expression — выражение, возвращающее объект Range.
  2. Across — логическое значение, определяющее характер объединения ячеек:
    • True — ячейки объединяются построчно: каждая строка заданного диапазона преобразуется в одну ячейку.
    • False — весь диапазон преобразуется в одну ячейку. False является значением по умолчанию.

Преимущество метода Range.Merge перед свойством MergeCells заключается в возможности построчного объединения ячеек заданного диапазона без использования цикла.

Свойство MergeCells

Свойство MergeCells объекта Range применяется как для объединения ячеек, так и для его отмены.

Синтаксис свойства с присвоением значения:

Expression.MergeCells = Boolean

  1. Expression — выражение, представляющее объект Range.
  2. Boolean — логическое значение, определяющее необходимость объединения ячеек или его отмены:
    • True — объединение ячеек заданного диапазона.
    • False — отмена объединения ячеек.

С помощью свойства MergeCells можно из кода VBA Excel проверять диапазон (отдельную ячейку), входит ли он (она) в объединенную ячейку (True) или нет (False). Если проверяемый диапазон окажется комбинированным, то есть содержащим объединенные и необъединенные ячейки, компилятор сгенерирует ошибку.

Переменная Expression для отмены объединения ячеек с помощью свойства Range.MergeCells может представлять одну любую ячейку, входящую в объединенный диапазон.

Метод Range.UnMerge

Метод UnMerge объекта Range разделяет объединенную область на отдельные ячейки из кода VBA Excel.

Синтаксис метода:

Expression — выражение, возвращающее объект Range.

Переменная Expression для отмены объединения ячеек методом UnMerge может представлять одну любую ячейку, входящую в объединенный диапазон.

Примеры объединения ячеек и его отмены

Пример 1
Наблюдаем, как происходит объединение ячеек при разных значениях параметра Across:

Sub Primer1()

‘Объединяем ячейки диапазона «A1:D4» построчно

   Range(«A1:D4»).Merge (True)

‘Объединяем диапазон «A5:D8» в одну ячейку

‘Across принимает значение False по умолчанию

   Range(«A5:D8»).Merge

End Sub

Не забываем, что логическое выражение True можно заменить единичкой, а False — нулем.

Пример 2
Отменяем объединение ячеек в диапазонах из первого примера:

Sub Primer2()

   Range(«A1:D8»).MergeCells = False

End Sub

Пример 3
Предполагается, что перед этим примером отменено объединение ячеек кодом из предыдущего примера.

Sub Primer3()

‘Объединяем ячейки диапазона «A1:D4»

   Range(«A1:D4»).MergeCells = 1

‘Проверяем принадлежность диапазона

‘объединенной ячейке*

   MsgBox Range(«A1:C2»).MergeCells

   MsgBox Range(«A6:C7»).MergeCells

‘Ячейки диапазона «A5:D8»

‘можно объединить и так

   Cells(5, 1).Resize(4, 4).Merge

End Sub

*Если проверяемый диапазон окажется комбинированным, VBA Excel сгенерирует ошибку.
Пример 4
Отмена объединения ячеек с помощью метода Range.UnMerge:

Sub Primer4()

‘Объединяем ячейки диапазона «A1:C4»

    Range(«A1:C4»).Merge

    MsgBox «Ячейки диапазона ««A1:C4»» объединены»

‘Смотрим адрес диапазона, входящего в объединенную ячейку

    MsgBox Range(«A2»).MergeArea.Address

‘Отменяем объединение ячеек диапазона «A1:C4»

    Range(«B3»).UnMerge  ‘или: Range(«B3»).MergeArea.UnMerge

    MsgBox «Объединение ячеек диапазона ««A1:C4»» отменено»

End Sub

Предупреждение перед объединением

Если объединяемые ячейки не являются пустыми, пред их объединением появится предупреждающее диалоговое окно с сообщением: «В объединенной ячейке сохраняется только значение из верхней левой ячейки диапазона. Остальные значения будут потеряны.»

Пример 5
Наблюдаем появление предупреждающего окна:

Sub Primer5()

‘Отменяем объединение ячеек в диапазоне «A1:D4»

   Range(«A1:D4»).MergeCells = 0

‘Заполняем ячейки диапазона текстом

   Range(«A1:D4») = «Ячейка не пустая»

‘Объединяем ячейки диапазона «A1:D4»

   Range(«A1:D4»).MergeCells = 1

‘Наблюдаем предупреждающее диалоговое окно

End Sub

Предупреждающее окно перед объединением ячеек

Чтобы избежать появление предупреждающего окна, следует использовать свойство Application.DisplayAlerts, с помощью которого можно отказаться от показа диалоговых окон при работе кода VBA Excel.

Пример 6

Sub Primer6()

‘Отменяем объединение ячеек в диапазоне «A5:D8»

   Range(«A5:D8»).MergeCells = 0

‘Заполняем ячейки диапазона «A5:D8» текстом

   Range(«A5:D8») = «Ячейка не пустая»

Application.DisplayAlerts = False

   Range(«A5:D8»).MergeCells = 1

Application.DisplayAlerts = True

End Sub

Теперь все прошло без появления диалогового окна. Главное, не забывать после объединения ячеек возвращать свойству Application.DisplayAlerts значение True.

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

I have a similar question to this one:

Merge the contents of 2 cells into another 3rd cell using VBA in Excel

But I want to combine a range of cells within a column, eg A2:A50. Sometimes I have over 300 cells to be combined into one. Values are text. Is there any way to modify this macro so that it works on a range instead of just two cells?

Thanks!

Community's user avatar

asked Jan 18, 2010 at 22:45

CCID's user avatar

Based on the thread you are citing, I guess you wish to return the concatination of all the values held by the cells, interpreting all the values as strings?

For that, you could use a VBA macro that looks like this:

Function ConcatinateAllCellValuesInRange(sourceRange As Excel.Range) As String
    Dim finalValue As String

    Dim cell As Excel.Range

    For Each cell In sourceRange.Cells
        finalValue = finalValue + CStr(cell.Value)
    Next cell

    ConcatinateAllCellValuesInRange = finalValue
End Function

As an example, you could call it like this:

Sub MyMacro()
    MsgBox ConcatinateAllCellValuesInRange([A1:C3])
End Sub

Is this what you were looking for?

Mike

Community's user avatar

answered Jan 18, 2010 at 23:18

Mike Rosenblum's user avatar

Mike RosenblumMike Rosenblum

12k6 gold badges48 silver badges64 bronze badges

Try the following macro, not very elegant in that it doesn’t do any error checking etc but works. Assign the macro to a button, click in a cell, click the macro button, highlight the desired (source) range to merge using your mouse (will autofill in range in the input box in the dialogue box), click ok, highlight the destination cell (will autofill the input box in the next dialogue box) click ok, all cells will be merged with a single space character into the destination cell, which can be in the original source range). Up to you to delete the superfluous cells manually. Workks with both rows and columns but not blocks.

Sub JoinCells()

Set xJoinRange = Application.InputBox(prompt:="Highlight source cells to merge",    Type:=8)
xSource = 0
xSource = xJoinRange.Rows.Count
xType = "rows"
If xSource = 1 Then
    xSource = xJoinRange.Columns.Count
    xType = "columns"
End If
Set xDestination = Application.InputBox(prompt:="Highlight destination cell", Type:=8)
If xType = "rows" Then
    temp = xJoinRange.Rows(1).Value
    For i = 2 To xSource
        temp = temp & " " & xJoinRange.Rows(i).Value
    Next i
Else
    temp = xJoinRange.Columns(1).Value
    For i = 2 To xSource
        temp = temp & " " & xJoinRange.Columns(i).Value
    Next i
End If

xDestination.Value = temp

End Sub

answered Aug 23, 2011 at 15:15

Paul McMahon's user avatar

Just to add to Mike’s solution, if you want to get your range from a variable instead of a defined range (I had trouble with the syntax):

Sub MyMacro()

dim myVar As Range

    MsgBox ConcatinateAllCellValuesInRange(myVar)

End Sub

answered Apr 13, 2015 at 9:55

HotSauceCoconuts's user avatar

Here is a macro developed circa 2006.
I still use it today!

Usage:

  • Select the cells you want to merge (the marco assumes they are all in the same column, one below the other)
  • Run the macro (a good idea is to assign it a short-cut key via Excel’s Developer->Code->Macros-> select the macro -> Options)
Sub MergeCells()
'
Dim myString As String
Dim myUnion As Range
    
   Count = Selection.Count
    
   myValue = Selection
    
   myrow = Selection.Row
   mycol = Selection.Column
   myString = ""
   
   For Index = 1 To Count
      If Index > 1 Then myString = myString & Chr(10) & myValue(Index, 1) Else myString = myValue(Index, 1)
   Next Index

  Selection.ClearContents
  Cells(myrow, mycol) = myString
  
  
' Uncomment this loop if you want to delete the rows that are below the top cell (the rows with the cells whose content was concatenated to the top cell)
' For Index = 1 To Count - 1
'    Rows(myrow + 1).Delete
' Next Index
    
 Cells(myrow, mycol).Select
       
End Sub

answered Mar 25 at 18:02

Michael Stahl's user avatar

Попробовал несколько подходов, вот результаты:
1. Самый быстрый подход, как и предполагалось — прямое сохранение листа в CSV файл (

тыц

)
Но, к сожалению, в моём случае этот «велосипед» не подошёл, т.к. требуемый формат более хитрый, и сохраняемые данные — это лишь часть сложного выходного файла.

2. Отлично показал себя подход с Join (

тыц

):

Код
 tc = GetTickCount
 ReDim arr(1 To N) As String
 For i = 1 To N
   arr(i) = i
 Next
 ss = Join(arr, "," ;) 
 Debug.Print GetTickCount - tc

Среднее время у меня получилось 6.3 мс на N=10000.

3. Примерно на том же уровне по скорости — подход с резервированием буфера и вставкой нужных строк по кусочкам при помощи MID (

тыц

)
Среднее время получилось 7.8 мс на N=10000.
Но у него есть недостаток — размер строкового буфера ограничен в 64К, а в моём случае это критично.

4. Исходный подход с итеративной склейкой — как и ожидалось, оказался очень тормозным.
Среднее время 102 мс на N=10000. Причём зависимость от N квадратичная, и это в моём случае самое неприятное!

5. Подход с буферизацией (

тыц

) интересен, но при каждом Print в файл записывается перевод строки.

6. Подход с заменой N итераций по Cells на одну выборку через Range(…).Value — взлетел отлично, спасибо! (

тыц

)

ИТОГ: удалось ускориться в десятки раз и, самое главное, избавиться от квадратичных зависимостей.
Всем спасибо огромное за помощь!!

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

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