如何使用 Excel VBA 将单元格值和文本连接在一起?

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

我有一项重复性任务想要自动执行,而不是一直使用 =Concatenate 函数。到目前为止,这是我的代码:

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

不幸的是,这会导致 "Compile error: Expected: end of statement" 错误,突出显示“-”。如何将文本“-”夹在这两个值之间?

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

@Joshua 为您的情况提供了答案。另一种更广泛的解决方案是我以前使用过的解决方案。请参阅此处复制的 UDF。

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

然后在您的 excel 文件中,只需使用此公式,选择要连接的单元格范围,并为其提供一个字符串(在本例中为“-”)以放入它们之间。

一个建议给谁需要:

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