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?
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.
There are two concatenation operators, + and & . Both carry out the basic concatenation operation, as the following example shows.
Cells(2, 5).Value = Cells(2, 1).Value & " - " & Cells(2, 2).Value
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With