2016-05-04 57 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