Excel - Concat直到 "文本"。

问题描述 投票:0回答:1

我有数据在1行,我想连接,但定义的范围之前的下一个单元格,包括单词 "模板"。

在下面,是一个例子,我是什么后。

Data and Desired Results

我看了一下帖子中的"如何在excel中连接单元格(行),直到找到一个值?"但我不知道为什么它对我不起作用。

谁能帮助我获得结果?

谢谢你!

excel excel-vba excel-formula
1个回答
0
投票
Sub test()

Dim cel As Range
Dim tail As String



For Each cel In ActiveSheet.UsedRange.Columns("A").Cells 'check each cell of the data column

If InStr(cel.Value, "template") <> 0 Then 'check if current cell contains the keyword "template"

  i = 1
  tail = ""

  'gather all the following cells that does not cotain the keyword as a string called "tail"
  Do While InStr(ActiveSheet.Cells(cel.Row + i, 1).Value, "template") = 0 And ActiveSheet.Cells(cel.Row + i, 1).Value <> ""
    tail = tail & ActiveSheet.Cells(cel.Row + i, 1).Value
      i = i + 1
  Loop

  ActiveSheet.Cells(cel.Row, 2).Value = cel.Value & tail 'final result

End If
Next cel


End Sub

这是一个粗糙的解决方案,但我认为它会工作。


0
投票

试试下面的代码。

Sub CustomConctat()
    Dim txt As String, lastRow As Long, i As Long, concatGroupStartRow As Long
    i = 1
    concatGroupStartRow = 1
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    Do While i < lastRow
        txt = txt + Cells(i, 1)
        ' If next row has template keyword, then insert concatenated text into
        ' first row in that group, in B column.
        If InStr(Cells(i + 1, 1), "template") Then
            Cells(concatGroupStartRow, 2).Value = txt
            txt = ""
            concatGroupStartRow = i + 1
        End If
        i = i + 1
    Loop
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.