Home / User Contributed Macros / Split Function

Split Function


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.

  1. Public Sub split_function()

  2.     'Declarations
  3.     Dim splitArr() As String
  4.     Dim sourceRng, destRng As Range
  5.     Dim destRow, destStartCol, destEndCol As Integer
  6.     Dim destSheet As String
  7.  
  8.     'Assigning Initial values
  9.     Set sourceRng = Sheet1.Range("A1:A3")     '  CommaSeperatedValues' Range 
  10.     destRow = 1
  11.     destStartCol = 1
  12.     destSheet = "Sheet2"
  13.  
  14.     For each cell in sourceRng                 ' Looping through all the cells in the source range
  15.  
  16.         If Not(IsEmpty(cell))    Then
  17.             splitArr = split(cell, ",")            '  Splitting the values
  18.  
  19.             destEndCol = UBound(splitArr) + 1
  20.  
  21.             'split values are pasted in destination range
  22.             Sheets(destSheet).Select                    
  23.             Set destRng = Sheets(destSheet).Range(Cells(destRow, destStartCol), Cells(destRow, destEndCol))
  24.             destRng.value = splitArr
  25.         End If
  26.  
  27.         destRow = destRow +1
  28.  
  29.     Next cell
  30.  
  31. End Sub




e.g


After splitting



     RSS of this page