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

依然范特西╮ 提交于 2020-01-22 19:29:25

问题


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?


回答1:


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




回答2:


@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.




回答3:


One suggestion for whom need:

Private Sub CommandButton1_Click()
Dim i As Long
Dim j As Long

Dim x As String

i = 1
j = Range("max").Value
x = Cells(i, 2)

For i = 2 To j

x = x & " - " & Cells(i, 2)

Next i

'MsgBox (x)

Range("d1").Value = x

i = 0

End Sub


来源:https://stackoverflow.com/questions/32054665/how-do-i-concatenate-cell-values-and-text-together-using-excel-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!