Skip to content

Instantly share code, notes, and snippets.

@peteristhegreat
Last active August 30, 2016 20:54
Show Gist options
  • Save peteristhegreat/4535aecca1dec2df8fb6844591517b65 to your computer and use it in GitHub Desktop.
Save peteristhegreat/4535aecca1dec2df8fb6844591517b65 to your computer and use it in GitHub Desktop.
Excel explode rows split rows based on a column vba script
Sub Main()
Call explode_rows("Sheet1", "Sheet2", 2, ",")
End Sub
Function explode_rows(sheet_src As String, sheet_dest As String, col As Integer, sep As String)
Dim wb As Workbook
Dim r_src As Integer
Dim r_dest As Integer
Dim str_array() As String
Dim x As Integer
Dim cell As Excel.Range
Set wb = ActiveWorkbook
r_dest = 1
' Set numrows = number of rows of data.
NumRows = wb.Sheets(sheet_src).Range("A1", Range("A1").End(xlDown)).Rows.Count
' Select cell a1.
' wb.Sheets(sheet_src).Range("A1").Select
' Establish "For" loop to loop "numrows" number of times.
For r_src = 1 To NumRows
Set cell = wb.Sheets(sheet_src).Cells(r_src, col)
str_array = Split(cell.Value2, sep)
' str_count = UBound(str_array, 1) - LBound(str_array, 1) + 1
Dim str As Variant
wb.Sheets(sheet_src).Rows(r_src).EntireRow.Copy
For Each str In str_array
wb.Sheets(sheet_dest).Cells(r_dest, 1).PasteSpecial xlPasteValues
' fix the split column
wb.Sheets(sheet_dest).Cells(r_dest, col).Value = CStr(str)
r_dest = r_dest + 1
Next str
' Selects cell down 1 row from active cell.
' ActiveCell.Offset(1, 0).Select
Next
End Function
Header 1 Header 2 Header 3
1 a apples
2 a bananas
3 a,b,c oranges
4 a, b, c fruit
5 d mangos
6 d,e,f durango
Header 1 Header 2 Header 3
1 a apples
2 a bananas
3 a oranges
3 b oranges
3 c oranges
4 a fruit
4 b fruit
4 c fruit
5 d mangos
6 d durango
6 e durango
6 f durango
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment