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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32054665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:54:53  来源:igfitidea点击:

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

excel-vbaexcel-2013vbaexcel

提问by xxxRxxx

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:

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

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?

不幸的是,这会导致“编译错误:预期:语句结束”错误,其中突出显示了“-”。我怎样才能将文本“-”夹在这两个值之间?

采纳答案by paul bica

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

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

回答by legendjr

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

@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

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.

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

回答by Truongpx

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