The following macro splits the strings by comma. It can be used to split strings based on other values(space, quote, etc.) too by modifying line no 18.
Strings with comma are present in Sheet1.A1:A3 and separated strings are placed in Sheet2.
- Public Sub split_function()
- 'Declarations
- Dim splitArr() As String
- Dim sourceRng, destRng As Range
- Dim destRow, destStartCol, destEndCol As Integer
- Dim destSheet As String
-
- 'Assigning Initial values
- Set sourceRng = Sheet1.Range("A1:A3") ' CommaSeperatedValues' Range
- destRow = 1
- destStartCol = 1
- destSheet = "Sheet2"
-
- For each cell in sourceRng ' Looping through all the cells in the source range
-
- If Not(IsEmpty(cell)) Then
- splitArr = split(cell, ",") ' Splitting the values
-
- destEndCol = UBound(splitArr) + 1
-
- 'split values are pasted in destination range
- Sheets(destSheet).Select
- Set destRng = Sheets(destSheet).Range(Cells(destRow, destStartCol), Cells(destRow, destEndCol))
- destRng.value = splitArr
- End If
-
- destRow = destRow +1
-
- Next cell
-
- End Sub
e.g
After splitting