Kevin Malloy
Kevin Malloy

Reputation: 183

Text to Rows VBA Excel

I have a spreadsheet with about a good 4000 rows of data, one of the columns of data has unique order numbers that I want separated using "/" as my delimiter. So essentially I want:

Name      Order#       Date
Jane      123/001/111  08/15/2013
Gary      333/121      09/01/2013
Jack      222          09/02/2013

To look like this:

Name      Order#       Date
Jane      123          08/15/2013
Jane      001          08/15/2013
Jane      111          08/15/2013
Gary      333          09/01/2013
Gary      121          09/01/2013
Jack      222          09/02/2013

I am fairly new to VBA, so I decided to try to Google for a solution where I came upon this nice bit of code.

        Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) 
    Dim ans 
    Dim Cels As Long, i As Long 
    Cancel = True 
    ans = Split(Target, ":") 
    Cels = UBound(ans) 
    Target.Offset(1).Resize(Cels).EntireRow.Insert shift:=xlDown 
    Rows(Target.Row).Copy Cells(Target.Row + 1, "A").Resize(Cels) 
    For i = 0 To Cels 
        Target.Offset(i) = ans(i) 
    Next 
End Sub

It works great but the way this macro functions is that you have to double click the row to separate the values. What I was hoping for is a way to pass this function through a For loop so it executes throughout the entire spreadsheet.

Upvotes: 4

Views: 6919

Answers (1)

user2140173
user2140173

Reputation:

If you sheet looks sort of like this

enter image description here

then

Option Explicit

Sub Main()

    Columns("B:B").NumberFormat = "@"
    Dim i As Long, c As Long, r As Range, v As Variant

    For i = 1 To Range("B" & Rows.Count).End(xlUp).Row
        v = Split(Range("B" & i), "/")
        c = c + UBound(v) + 1
    Next i

    For i = 2 To c
        Set r = Range("B" & i)
        Dim arr As Variant
        arr = Split(r, "/")
        Dim j As Long
        r = arr(0)
        For j = 1 To UBound(arr)
            Rows(r.Row + j & ":" & r.Row + j).Insert Shift:=xlDown
            r.Offset(j, 0) = arr(j)
            r.Offset(j, -1) = r.Offset(0, -1)
            r.Offset(j, 1) = r.Offset(0, 1)
        Next j
    Next i

End Sub

will produce

enter image description here

Upvotes: 4

Related Questions