2015-05-20 56 views
1

我想將單元格A1:A100中的數字連接到單個字符串中。我該怎麼做,參考另一張表。代碼如下VBA中的連接

Sheets("Current").Cells(1,1).Formula = "=CONCATENATE('Reference Sheet'!A1:A100)" 

但我沒有得到任何東西。請幫助

+0

你想把結果字符串放在哪裏? – moffeltje

回答

3

其單行:

MsgBox Join(Application.Transpose(Range("A1:A100")), vbNullString) 
+0

謝謝你的作品,是否可以在每個單元格值之間添加一個空格,因爲這會導致連續的單元格值? – Meesha

+0

@meesha用chr替換vbnullstring(32) – brettdj

+0

謝謝你的幫助。 – Meesha

2
Dim oRng As Range 
Dim cel As Range 
Dim concStr as String 

Set oRng = Range("A1:A100") 
concStr = vbNullString 

For Each cel in oRng 

    concStr = concStr & cel.value 

Next cel 

''Do stuff with concStr 
0

CONCATENATE功能並不在範圍內,但在不同的細胞,即CONCATENATE('Reference Sheet'!A1,'Reference Sheet'!A2,'Reference Sheet'!A3)工作。如果你總是有100個細胞,那麼你可以使用一個循環:

Dim x As Integer 
Dim formulaString As String 

formulaString= "=CONCATENATE(" 
For x = 1 To 100 
    formulaString= formulaString & "'Reference Sheet'!A" & x & "," 
Next x 
' Remove last comma 
formulaString= Left(formulaString, Len(formulaString) - 1) 
' Add closing bracket 
formulaString= formulaString& ")" 
Sheets("Current").Cells(1,1).Formula = formulaString 
0

使用數組,首先創建一個數組來保存輸入值"A1:A100"。 然後將數組中的所有數字轉換爲字符串並加入數組以獲得結果字符串並將其輸入到所需的單元格中。

對於使用工作表這個代號爲「源」和 「目標」 (修改根據需要)

請您檢查代碼中的註釋,看看

https://msdn.microsoft.com/en-us/library/office/gg264098.aspx

Sub Rng_ConcatenateValues() 
Dim aArySrc As Variant, vArySrc As Variant, sAryTrg As String 
Dim l As Long 

    With ActiveWorkbook 
     Rem Set Input Array 
     aArySrc = WorksheetFunction.Transpose(.Worksheets("Source").Range("A1:A100")) 
     Rem Convert values to string 
     For l = LBound(aArySrc) To UBound(aArySrc) 
      aArySrc(l) = CStr(aArySrc(l)) 
     Next 
     Rem Join Array Values 
     sAryTrg = Join(aArySrc, Chr(133)) 
     Rem Post Resulting Concatenation 
     .Worksheets("Target").Cells(1).Value = sAryTrg 
    End With 
End Sub