Search code examples
excelvba

How to separate dates in wrapped cell by line break?


I have comment data in column A:

enter image description here

Desired result:

enter image description here

I'm trying to loop through cells in col A and separate the comment to look like what you see in col B (line break every time a date appears Instr).

Here's the code I tried, but it ran through and didn't do anything. I figure I'm sort of on my way to getting it working, but this wasn't an easy problem to research online as I haven't seen other posts attempting this.

Code I tried to piece together to get an idea:

Sub Line_Breaks()

Dim c As Range
Dim searchstring As String
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sheet1")
searchstring = Format(Sheet1.Cells(1, 2).Value, "m/d/yyyy")

    For Each c In ws.UsedRange.Columns("A").Cells
            If InStr(1, c.Value, searchstring) Then
                c.Value = Split(c.Value, vbNewLine)
            End If
        
    Next c
    
End Sub

Solution

    • RegExp pattern matchs the desired string, but the code does NOT validate if it is a valide date. eg. 99/99/99 will be considered as a matched string.

    • The code writes the ouput to Col B. You can modify it to update Col A.

    Option Explicit
    Sub Demo()
        Dim i As Long, oSht As Worksheet, sTxt As String
        Dim lastRow As Long, objRegExp As Object
        Set objRegExp = CreateObject("vbscript.regexp")
        Set oSht = Sheets("Sheet1")
        lastRow = oSht.Cells(oSht.Rows.Count, "A").End(xlUp).Row
        With objRegExp
            .Global = True
            .Pattern = "(\d{1,2}/\d{1,2}/\d{2,4})"
            For i = 2 To lastRow
                sTxt = Trim(oSht.Cells(i, 1))
                If .Test(sTxt) Then
                    sTxt = .Replace(sTxt, Chr(10) & "$1")
                    If Left(sTxt, 1) = Chr(10) Then sTxt = Mid(sTxt, 2)
                    oSht.Cells(i, 2) = sTxt
                    ' Update Col A
    '                oSht.Cells(i, 1) = sTxt
                End If
            Next
        End With
    End Sub
    

    enter image description here