Victoria G
Victoria G

Reputation: 81

Split Cells by Line Break VBA

I have a dataset with 40 columns and ~5000 rows. In columns L and M there are multiline cells with line breaks, and I need to split these lines into separate rows but keep the information in the other columns the same for these new rows. I have tried multiple VBA codes but none seem to do the trick for two columns.

Upvotes: 1

Views: 3948

Answers (1)

Miqi180
Miqi180

Reputation: 1691

This will work for numbers and strings, but not for formulas. It's also not suitable for formatted cells:

Sub multilineCellsToSeparateCells(rng As Range)

        Dim i As Long, j As Long, ubnd As Long
        Dim cll As Range
        Dim arrVals As Variant, tempVal As Variant, vItem As Variant

        With rng

            ReDim arrVals(.Rows(1).Row To rng.Rows.Count, 1 To 1) As Variant
            For Each cll In rng.Cells
                tempVal = cll.Value2
                If InStr(1, tempVal, Chr(10)) > 0 Then
                    vItem = Split(tempVal, Chr(10))
                    i = i + 1
                    ubnd = UBound(vItem)
                    For j = 0 To ubnd
                        arrVals(i + j, 1) = vItem(j)
                    Next j
                    i = i + ubnd

                ElseIf tempVal <> vbNullString Then
                    i = i + 1
                    arrVals(i, 1) = tempVal
                End If

            Next cll

            .Value2 = arrVals
            .AutoFit ' optional

        End With

End Sub

Example

Write this in Column A:

A1: 1
A2: 2
A3: 3
A4: This
    is
    a 
    test
A5: 5

Invoke the Sub and the output will be:

A1: 1
A2: 2
A3: 3
A4: This
A5: is
A6: a 
A7: test
A8: 5

The sub fixes one column at a time. Invoke it like this:

Call multilineCellsToSeparateCells(Activesheet.Columns("A"))

Upvotes: 2

Related Questions