VBA macros · Workbooks and files
VBA macro to split a sheet into workbooks by column value
Split one data sheet into a separate workbook for every region, department or customer in a column, saved next to the original file.
A master list with every region, branch or salesperson often has to be sent out in pieces: each manager should get only their own rows. Filtering, copying and saving each group by hand is slow and error-prone. This macro reads the distinct values in one column, filters the sheet for each value, copies the rows to a new workbook and saves it as North.xlsx, South.xlsx and so on, in the same folder as the original.
Option Explicit
Sub SplitSheetByColumnValue()
Const KEY_COL As Long = 1 ' column to split by (1 = A)
Dim src As Worksheet
Dim data As Range
Dim lastRow As Long, lastCol As Long, r As Long
Dim keys As Collection
Dim k As Variant
Dim wbNew As Workbook
Dim folder As String
Dim made As Long
Set src = ActiveSheet
If Len(src.Parent.Path) = 0 Then
MsgBox "Save the workbook first; the files go into its folder.", vbExclamation
Exit Sub
End If
folder = src.Parent.Path & Application.PathSeparator
If src.AutoFilterMode Then src.AutoFilterMode = False
lastRow = src.Cells(src.Rows.Count, KEY_COL).End(xlUp).Row
lastCol = src.Cells(1, src.Columns.Count).End(xlToLeft).Column
If lastRow < 2 Then Exit Sub
Set data = src.Range(src.Cells(1, 1), src.Cells(lastRow, lastCol))
' Collect each distinct value once (duplicate keys raise an error we ignore)
Set keys = New Collection
On Error Resume Next
For r = 2 To lastRow
k = src.Cells(r, KEY_COL).Text
If Len(k) > 0 Then keys.Add k, CStr(k)
Next r
On Error GoTo Fail
Application.ScreenUpdating = False
Application.DisplayAlerts = False ' overwrite existing files silently
For Each k In keys
data.AutoFilter Field:=KEY_COL, Criteria1:="=" & k
Set wbNew = Workbooks.Add(xlWBATWorksheet)
data.SpecialCells(xlCellTypeVisible).Copy wbNew.Worksheets(1).Range("A1")
wbNew.Worksheets(1).Name = CleanName(CStr(k))
wbNew.Worksheets(1).UsedRange.Columns.AutoFit
wbNew.SaveAs Filename:=folder & CleanName(CStr(k)) & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook
wbNew.Close SaveChanges:=False
Set wbNew = Nothing
made = made + 1
Next k
src.AutoFilterMode = False
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox made & " workbook(s) saved in " & folder, vbInformation
Exit Sub
Fail:
If Not wbNew Is Nothing Then wbNew.Close SaveChanges:=False
src.AutoFilterMode = False
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Stopped at '" & k & "': " & Err.Description, vbExclamation
End Sub
Private Function CleanName(ByVal s As String) As String
' Replaces characters that are not allowed in file or sheet names
Dim ch As Variant
For Each ch In Array("\", "/", ":", "*", "?", """", "<", ">", "|", "[", "]")
s = Replace(s, ch, "_")
Next ch
CleanName = Left$(Trim$(s), 31)
End FunctionHow to use it
- Open the workbook and press
Alt+F11(Mac:Opt+F11orFn+Opt+F11) to open the VBA editor. See The Developer tab and the VBA editor if you have never used it. - Choose Insert › Module. An empty code window opens on the right.
- Paste the whole code into that window. If the module already starts with
Option Explicit, do not paste that line twice. - Go back to Excel, press
Alt+F8(Mac:Opt+F8, or Tools › Macro › Macros), pickSplitSheetByColumnValueand click Run. - Set
KEY_COLto the column number to split by, save the workbook once, make the data sheet active, then run the macro. - Save the file as an Excel Macro-Enabled Workbook (.xlsm). A normal .xlsx file throws the code away when you save it.
How it works
The macro needs a saved workbook because the new files go into the same folder (src.Parent.Path). It assumes the data starts in A1 with headings in row 1, and it finds the last row and column with End(xlUp) and End(xlToLeft).
Distinct values are collected in a Collection. Adding an item with a key that already exists raises an error, and On Error Resume Next simply ignores it, so every value ends up in the collection exactly once, in the order it first appears. The values are taken from .Text, which is what the cells show.
For each value, AutoFilter with Criteria1:="=" & k shows only the matching rows (the = asks for an exact match). SpecialCells(xlCellTypeVisible) then picks the heading row plus the visible data rows, and .Copy with a destination pastes them into the single sheet of a new workbook. The sheet and the file get the value as their name, cleaned of characters that names may not contain.
DisplayAlerts = False stops the file already exists question, so running the macro again replaces the files. The Fail handler closes a half-finished workbook, removes the filter and switches alerts back on whatever happens. AutoFilter in VBA is explained in Find, filter and sort data with VBA.
Change it
Useful variations:
- Split into sheets of the same workbook instead of files: replace the
Workbooks.Addblock withSet ws = ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)), copy tows.Range("A1")and namews. - Save into a subfolder: build
folder = src.Parent.Path & Application.PathSeparator & "Split" & Application.PathSeparatorand create it first withIf Len(Dir(folder, vbDirectory)) = 0 Then MkDir folder. - Keep column widths exactly: after the copy add
data.Rows(1).CopyandwbNew.Worksheets(1).Range("A1").PasteSpecial xlPasteColumnWidths. - Add a date to every file name:
CleanName(CStr(k)) & " " & Format(Date, "yyyy-mm-dd") & ".xlsx".
To send each file by email right after saving it, combine this macro with VBA macro to send the active workbook by Outlook email.
What can go wrong
The filter compares the displayed text. Values containing * or ? act as wildcards and may match more rows than expected, and numbers or dates with unusual formats can fail to match. The macro works best on a text column such as region or department; for dates, add a helper column with =TEXT(B2,"yyyy-mm") and split on that.
Formulas in the copied rows that point to other sheets become links to the original workbook. If the recipients should only see values, add wbNew.Worksheets(1).UsedRange.Value2 = wbNew.Worksheets(1).UsedRange.Value2 before saving.
Related: VBA macro to save each sheet as a separate workbook in Excel, VBA macro to merge all workbooks in a folder into one sheet, Find, filter and sort data with VBA.