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 

我能怎么做 ? 提前致谢 !

 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 

以下是你所要求的,而且更具通用性:

  • 它将列“A”的所有单元格与其中的一些文本考虑在内

  • 它将内容的范围扩展到给定行中所有连续的非空白单元格

换句话说,这种方法既不会受到列数的任何可能变化的影响(它们可以是3,按照您的例子,或者更多或更less),也不受所有行具有相同数量的单元格填充的情况的影响

 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 
 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