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

时间:2017-01-29 07:14:44

标签: excel vba excel-vba

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

请参阅图片:col_A has the data, col_C and col_D are the desired result

2 个答案:

答案 0 :(得分:2)

你可以这样做。我无法保证,因为我只在您的样品盒上进行了测试。因此,它不适用于非连续编号的子条目 - 也不适用于子条目不合规的情况。当然,后者都可以合并到一个更强大的版本中,您必须自己重构。实际上,如果要实现后者,正则表达式已经获取了子条目#。

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语句查找子条目的开头,一旦找到,就会进入内部循环,将它们添加到&#39;项目&#39;采集。找到最后一个之后,将集合连接起来并存储在主条目的保存位置(&#39; rowPtr&#39;)。另请注意列&#39; A&#39;并且查看的最大行数(maxRow)被硬编码到宏中。

答案 1 :(得分:0)

您可以使用http://my.domain.com/ => http://127.0.0.1:9200; http://my.domain.com/_plugin/kibana => http://127.0.0.1:9200/_plugin/kibana 方法和AutoFilter()对象的Areas属性

Range
相关问题