如何在Excel VBA中连接相邻的单元格

我有一个列中的数据。 有些单元格以“index”开始,如:(1),(2)等。我想按顺序连接这些单元格,并将结果放到下一列,并清除原始单元格。 你能告诉我如何在VBA中做到这一点? 谢谢!

请看图: col_A有数据,col_C和col_D是想要的结果

你可以做这样的事情。 我不能担保,因为我只在你的案例中进行过testing。 所以它不适用于非连续的编号子条目 – 也不适用于子条目不合适的情况。 当然,后面的两个都可以被合并到一个更强大的版本中,你必须自己重构。 实际上,正则expression式已经拿起子条目#如果你想实现后者。

 Sub process() Dim maxRow As Integer: maxRow = 100 Dim items As Collection Dim regEx As Object Dim matches As Object Set items = New Collection Set re = CreateObject("vbscript.regexp") re.Global = True re.IgnoreCase = True re.Pattern = "\((\d+)\).*" Dim val As String Dim row As Integer, rowPtr As Integer: row = 1 Dim matchTest As Boolean, preMatchTest As Boolean: preMatchTest = False Do While row < maxRow: val = Cells(row, "A").Value matchTest = re.Test(val) If Not preMatchTest And matchTest Then rowPtr = row Do While row < maxRow + 1: val = Cells(row, "A").Value matchTest = re.Test(val) If matchTest Then Set matches = re.Execute(val) itemNum = matches(0).submatches(0) items.Add val Cells(row, "A") = "" Else For Each colVal In items: Cells(rowPtr - 1, "B") = Cells(rowPtr - 1, "B") & colVal Next Set items = New Collection Exit Do End If row = row + 1 preMatchTest = matchTest Loop End If preMatchTest = False row = row + 1 Loop End Sub 

prematch / match if语句查找子条目的开始,一旦find,就会进入将其添加到“items”集合的内部循环。 在find最后一个之后,集合被连接并存储在主条目的保存位置(“rowPtr”)处。 还要注意,列“A”和查看的最大行数(maxRow)被硬编码到macros中。

你可以使用AutoFilter()方法和Range对象的Areas属性

 Option Explicit Sub main() Dim area As Range With Range("A1", Cells(Rows.Count, 1).End(xlUp)).Offset(, 2) .Offset(, -2).Copy .Cells .AutoFilter Field:=1, Criteria1:="(*" If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then For Each area In .Resize(.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible).Areas area(1).Offset(-1, 1).Value = Join(Application.Transpose(area.Value), "") area.ClearContents Next End If .Parent.AutoFilterMode = False End With End Sub