2016-05-04 55 views
0

我想連接列,但在VBA的第一列,這樣的:VBA - 串聯列第一列

A   | B   | C   | 
sentence1 | sentence2 | sentence3 | 
sentence4 | sentence5 | sentence6 | 
sentence7 | sentence8 | sentence9 | 

- >

A        | B  | C  
sentence1 sentence2 sentence3 | nothing | nothing 
sentence4 sentence5 sentence6 | nothing | nothing 
sentence7 sentence8 sentence9 | nothing | nothing 

我該怎麼辦? 在此先感謝!

回答

1
Dim tempval As String 

Dim row As Integer, col As Integer 

Application.ScreenUpdating = False 

'loop through rows 
For row = 1 To 3 Step 1 

    'clear temp string 
    tempval = "" 

    'loop through columns 
    For col = 1 To 3 Step 1 

     'save columnvalues in temp 
     tempval = tempval & Cells(row, col).Value 

     'delete cell value 
     Cells(row, col).Value = "" 
    Next col 

    'paste saved string into first cell 
    Cells(row, 1).Value = tempval 
Next row 

Application.ScreenUpdating = True 
+0

非常感謝! :) – Ikanagura

0
Dim r As Range 
For Each r In Sheet1.UsedRange 
    r(1, 1).Value = r(1, 1).Value & " " & r(1, 2).Value & " " & r(1, 3).Value 
    r(1, 2).Value = "" 
    r(1, 3).Value = "" 
Next r 
+1

不應該在for..each循環中添加'.row'嗎? – Jochen

+0

不,因爲我們在這裏使用範圍而不是ListRows。 – jsheeran

1

以下做你問什麼,是在一個小更通用:

  • 它在它考慮到列「A」的所有細胞與一些文本

  • 它將內容的範圍擴展到給定行中所有連續的非空白單元格

換句話說,這種方法既不會受到列數的任何可能變化的考慮(它們可以是3,根據您的示例或更多或更少),也不受所有行具有相同的條件的影響填充單元格的數量

Option Explicit 

Sub main() 
Dim cell As Range 

With Worksheets("mySheet").Columns("A").SpecialCells(xlCellTypeConstants, xlTextValues) 
    For Each cell In .Cells 
     cell.Value = Join(Application.Transpose(Application.Transpose(Range(cell, cell.End(xlToRight))))) 
     Range(cell.Offset(, 1), cell.End(xlToRight)).Clear 
    Next cell 
    .WrapText = False 
    .EntireColumn.AutoFit 
End With 

End Sub 
+0

謝謝,但我已經在寫這個之前解決了解決方案。對不起! – Ikanagura

+0

不客氣。您無需發佈您的解決方案,以便讓其他用戶從中受益。乾杯 – user3598756