Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate cell values and text together using Excel VBA?

I have a repetitive task I'd like to automate instead of using the =Concatenate function all the time. Here's my code so far:

Cells(2, 5).Value = Cells(2, 1).Value&" - "&Cells(2, 2).Value

Unfortunately this results in the "Compile error: Expected: end of statement" error, which highlights the " - ". How can I sandwich that text, " - ", between those two values?

like image 610
xxxRxxx Avatar asked Aug 17 '15 15:08

xxxRxxx


People also ask

How do I concatenate a string and cell value in Excel 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.

Which operator is used for concatenation in VBA?

There are two concatenation operators, + and & . Both carry out the basic concatenation operation, as the following example shows.


2 Answers

Cells(2, 5).Value = Cells(2, 1).Value & " - " & Cells(2, 2).Value

like image 191
paul bica Avatar answered Sep 18 '22 09:09

paul bica


@Joshua provided an answer for you situation. Another solution that is more broad is one I've used before. See the UDF copied here.

Option Explicit
Function ConcatenateRow(rowRange As Range, joinString As String) As String
    Dim x As Variant, temp As String

    temp = ""
    For Each x In rowRange
        temp = temp & x & joinString
    Next

    ConcatenateRow = Left(temp, Len(temp) - Len(joinString))
End Function

Then in your excel file, just use this formula, selecting the range of cells to join, and giving it a string (in this case " - ") to put in between them.

like image 29
legendjr Avatar answered Sep 18 '22 09:09

legendjr