我有一个重复的任务,希望用自动化方式代替每次使用=Concatenate函数。以下是我的代码:
Cells(2, 5).Value = Cells(2, 1).Value&" - "&Cells(2, 2).Value
很遗憾,这导致出现“编译错误:应为语句结尾”的错误,突出显示“ - ”。我该如何将文本“ - ”夹在这两个值之间?
我有一个重复的任务,希望用自动化方式代替每次使用=Concatenate函数。以下是我的代码:
Cells(2, 5).Value = Cells(2, 1).Value&" - "&Cells(2, 2).Value
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
Cells(2, 5).Value = Cells(2, 1).Value & " - " & Cells(2, 2).Value
。 - Soulfire