excelvbaconcatenation

Excel: VBA script to concatenate text until the next cell that starts with a number?


In Excel I have the data as shown in columns A and B.

I would like to automatically populate the data shown in column C.

A B C - desired result
01/Feb/2024 Text 1 Text 1
01/Feb/2024 Text 2 Text 2, Text 3, Text 4, Text 5, Text 6
Text 3
Text 4 Text 5
Text 6
01/Feb/2024 Text 7 Text 7
01/Feb2024 Text 8 Text 8

I'm really struggling to write a VBA script to do this. Please can someone help?

I tried the following script:

Sub ConcatenateUntilNumber()

    Dim ws As Worksheet
    Dim lastRow As Long
    Dim i As Long
    Dim result As String
    
 
    Set ws = ThisWorkbook.Sheets("Sheet3")
    
    
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    
    
    result = ""
    
    
    For i = 1 To lastRow
    
        If ws.Cells(i, 1).Value <> "" Then
        
            If IsNumeric(Left(ws.Cells(i, 1).Value, 1)) Then
            
                If result <> "" Then
                    ws.Cells(i, 3).Value = result 
                End If
                result = "" 
            Else
                
                If result = "" Then
                    result = ws.Cells(i, 1).Value & " " & ws.Cells(i, 2).Value
                Else
                    result = result & ", " & ws.Cells(i, 1).Value & " " & ws.Cells(i, 2).Value
                End If
            End If
        End If
    Next i
    
End Sub

But this is the only result:

A B C - result
01/Feb/2024 Text 1
01/Feb/2024 Text 2
Text 3
Text 4 Text 5
Text 6
01/Feb/2024 Text 7 Text 3, Text 4 Text 5, Text 6
01/Feb/2024 Text 8

Solution

  • If you have access to MS365 then perhaps you can accomplish the desired output using the following formula as well:

    enter image description here


    • Formula used in cell C2

    =LET(
         a, A2:B8,
         b, TAKE(a,,1),
         c, ISERR(--b),
         d, SCAN(0,1-c,LAMBDA(x,y,IF(y,x+1,x))),
         e, IF(1-c,MAP(d,LAMBDA(z, TEXTJOIN(", ",1,IF(ISERR(--a)*(z=d),a,"")))),""),
         e)