2015-08-17 106 views
4

我有一個重複的任務,我想自動化,而不是始終使用= Concatenate函數。這裏是我到目前爲止的代碼:如何使用Excel VBA連接單元格值和文本?

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

不幸的是這導致了「編譯錯誤:預期:語句結束」錯誤,這凸顯了「 - 」。我如何在這兩個值之間夾入文本「 - 」?

+5

你需要你的符號和引號之間的空格,如:細胞(2,5).value的=細胞(2,1).value的&'「 - 「&Cells(2,2).Value' – Soulfire

回答

5

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

0

@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文件

然後,就用這個公式,選擇細胞加入的範圍,並賦予它一個字符串(在這種情況下,「 - 」),把它們之間。

1

一個建議對他們來說,需要:

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 
相關問題