Export Split Data
Sub ExportSplitData()
' Define constants.
Const SRC_NAME As String = "Sheet1"
Const SRC_FIRST_CELL As String = "A5"
Const SRC_CRITERIA_COLUMN As Long = 1
Const DST_FOLDER As String _
= "Z:\Incent_2022\ORDINARIA\RETAIL-WHS\Andamento\Q4\Andamento\Novembre\"
Const DST_NAME_LEFT As String = "And. Inc Q4_"
Const DST_EXTENSION As String = ".xlsm"
' Reference the Source worksheet.
Dim swb As Workbook: Set swb = ThisWorkbook ' workbook containing this code
Dim sws As Worksheet: Set sws = swb.Sheets(SRC_NAME)
Application.ScreenUpdating = False
' To leave the source workbook intact, export the worksheet
' to a new (helper) workbook and reference the range (there).
sws.Copy
Dim hwb As Workbook: Set hwb = Workbooks(Workbooks.Count)
Dim hws As Worksheet: Set hws = hwb.Sheets(SRC_NAME)
If hws.FilterMode Then hws.ShowAllData
Dim hfCell As Range: Set hfCell = hws.Range(SRC_FIRST_CELL)
Dim hrg As Range, hdrg As Range, hfrrg As Range, hrCount As Long
With hws.UsedRange
Set hfrrg = Intersect(hfCell.EntireRow, .Cells)
Set hrg = hfrrg.Resize(.Rows.Count + .Row - hfrrg.Row)
hrCount = hrg.Rows.Count
Set hdrg = hrg.Resize(hrCount - 1).Offset(1) ' no headers
End With
' Sort the range by the criteria column.
hrg.Sort hrg.Columns(SRC_CRITERIA_COLUMN), xlAscending, , , , , , xlYes
' Write the unique values from the criteria column to a dictionary.
Dim hData() As Variant: hData = hdrg.Columns(SRC_CRITERIA_COLUMN).Value
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
dict.CompareMode = vbTextCompare
Dim r As Long
For r = 1 To hrCount - 1
If Len(CStr(hData(r, 1))) > 0 Then
dict(hData(r, 1)) = Empty
End If
Next r
' Loop through the keys of the dictionary and export
' the sorted helper worksheet to be processed in yet another file,
' the destination workbook.
Dim dwb As Workbook, dws As Worksheet, drg As Range, ddrg As Range
Dim rKey As Variant, dFilePath As String
For Each rKey In dict.Keys
hws.Copy
Set dwb = Workbooks(Workbooks.Count)
Set dws = dwb.Sheets(SRC_NAME)
Set drg = dws.Range(hrg.Address) ' has headers
Set ddrg = dws.Range(hdrg.Address) ' no headers
drg.AutoFilter SRC_CRITERIA_COLUMN, "<>" & rKey ' filter
ddrg.SpecialCells(xlCellTypeVisible).Delete xlShiftUp ' delete
dws.AutoFilterMode = False ' turn off filter
dFilePath = DST_FOLDER & DST_NAME_LEFT & rKey & DST_EXTENSION
Application.DisplayAlerts = False
dwb.SaveAs dFilePath, xlOpenXMLWorkbookMacroEnabled
Application.DisplayAlerts = True
dwb.Close SaveChanges:=False
Next rKey
' Close the helper file.
hwb.Close SaveChanges:=False
Application.ScreenUpdating = True
' Inform.
MsgBox "Split data exported.", vbInformation
End Sub