i have excel file contain 20 columns, i need seperate files with same column by example column 12, ex:
for row 1 to row 100 col12=5100, i need all row in seperate file 5100.xlsx and etc. How with vba?
Assistant
You want to split your Excel data based on the value in column 12, and export rows with the same column 12 value into separate Excel files named after that value.
Here is a VBA macro that does this:
vba
Sub ExportByColumn12()
Dim wb As Workbook
Dim ws As Worksheet
Dim dict As Object
Dim lastRow As Long
Dim i As Long
Dim key As Variant
Dim savePath As String
Dim newWb As Workbook
Dim dataRange As Range
Dim headerRange As Range
Dim arr As Variant
Set wb = ThisWorkbook
Set ws = wb.Sheets(1) ' change if your data is in another sheet
' Find last used row
lastRow = ws.Cells(ws.Rows.Count, 12).End(xlUp).Row
' Get header (assuming headers in row 1)
Set headerRange = ws.Range(ws.Cells(1, 1), ws.Cells(1, 20))
' Create a dictionary to store unique values in column 12 with their row numbers
Set dict = CreateObject("Scripting.Dictionary")
' Loop through rows and collect row indexes for each unique value in column 12
For i = 2 To lastRow
key = ws.Cells(i, 12).Value
If Not dict.exists(key) Then
dict.Add key, Array(i)
Else
arr = dict(key)
ReDim Preserve arr(UBound(arr) + 1)
arr(UBound(arr)) = i
dict(key) = arr
End If
Next i
' Folder to save files - change as needed
savePath = wb.Path & "\"
If savePath = "\" Then
MsgBox "Please save the current workbook first."
Exit Sub
End If
Application.ScreenUpdating = False
' For each unique value, create new workbook and copy relevant rows
For Each key In dict.keys
Set newWb = Workbooks.Add
With newWb.Sheets(1)
' Copy header
headerRange.Copy .Range("A1")
' Copy rows for current key
Dim rowNums As Variant
rowNums = dict(key)
Dim destRow As Long
destRow = 2
Dim rw As Long
For Each rw In rowNums
ws.Range(ws.Cells(rw, 1), ws.Cells(rw, 20)).Copy .Cells(destRow, 1)
destRow = destRow + 1
Next rw
.Columns.AutoFit
End With
' Save new workbook
On Error Resume Next
newWb.SaveAs Filename:=savePath & key & ".xlsx", FileFormat:=51 ' xlOpenXMLWorkbook = 51
If Err.Number <> 0 Then
MsgBox "Error saving file: " & savePath & key & ".xlsx"
Err.Clear
End If
On Error GoTo 0
newWb.Close SaveChanges:=False
Next key
Application.ScreenUpdating = True
MsgBox "Export completed!"
End Sub
How to use:
Open your Excel file.
Press ALT + F11 to open the VBA editor.
Insert a new module: Insert > Module.
Paste the code above into the module.
Save your workbook (important, so it has a path to save files).
Press F5 to run the macro or run it from Excel.
This will create separate files named after each unique value in column 12 (5100.xlsx, etc.) in the same folder where your current workbook is saved. Each file will include the original 20 columns and their matching rows.
If your data headers are not in row 1, or columns number is different, adjust headerRange and ws.Cells() accordingly. Let me know if you want the macro to handle that too.
User
error ---------------------------
Microsoft Visual Basic for Applications
Compile error:
For Each control variable must be Variant or Object
OK Help
Assistant
The error message "For Each control variable must be Variant or Object" happens because you declared your loop variable as a specific data type (e.g., Long), but For Each loops require the loop variable to be a Variant or Object type.
In your code, the variable rw is declared as Long and is used in a For Each loop, which is not allowed.
Here is the fix:
Change this line:
vba
Dim rw As Long
to
vba
Dim rw As Variant
Corrected code snippet:
vba
Dim rw As Variant
For Each rw In rowNums
ws.Range(ws.Cells(rw, 1), ws.Cells(rw, 20)).Copy .Cells(destRow, 1)
destRow = destRow + 1
Next rw
Full corrected macro so you can copy-paste:
vba
User
it`s very very slow for 1000000 record
Assistant
If you have about 1,000,000 rows, the current VBA macro that loops row-by-row and copies rows individually will indeed be very slow.
Key reasons for slowness:
Looping row by row in VBA is slow.
Copying/pasting rows one at a time is inefficient.
Writing a new workbook for each unique value slows things down, especially if there are many groups.
How can we make it faster?
1. Use Arrays to minimize worksheet interactions
Load the entire data range into a VBA array once. Process data in memory (faster).
2. Group rows by key inside arrays, then write batch data at once to new workbooks.
3. Use AutoFilter method to quickly filter rows by column 12 value — very efficient.
4. Turn off ScreenUpdating, Calculation, EnableEvents and restore afterwards.
Here is a much faster version using AutoFilter and batch copy for large datasets:
vba
User
change code when columns 20 or more or less. calculate dynamic
Assistant
Absolutely! To handle a dynamic number of columns (instead of fixed 20), you can detect the last used column and export all columns accordingly.
I updated the last code with dynamic column detection (based on the last used column in the header row). That way, whether you have 10 columns or 50 columns, it automatically adjusts.
Updated code with dynamic last column detection:
vba
User
and if wanna save as %filename_5100 and ete?
Assistant
If you want to save files with a prefix before the value in column 12, for example filenames like:
' ... inside the For Each key loop
On Error Resume Next
newWb.SaveAs Filename:=savePath & "filename_" & CleanFileName(key) & ".xlsx", FileFormat:=51
If Err.Number <> 0 Then
MsgBox "Error saving file: " & savePath & "filename_" & key & ".xlsx"
Err.Clear
End If
On Error GoTo 0
Bonus: If you want to make the prefix flexible (input by user), you can add code like this at the beginning of the Sub:
vba
Dim prefix As String
prefix = InputBox("Enter filename prefix (e.g., filename_)", "Filename prefix", "filename_")
If prefix = "" Then prefix = "filename_"
Let me know if you want me to provide the full updated macro including this prefix input!
User
error :
Microsoft Visual Basic for Applications
Compile error:
ByRef argument type mismatch
OK Help
Assistant
This error usually happens when you call a procedure or function and pass an argument whose type doesn't match the argument's formal parameter declared as ByRef.
Optional: Also change the parameter type in the function to Variant to be safer:
vba
Function CleanFileName(fileName As Variant) As String
and inside it use
vba
Dim strName As String
strName = CStr(fileName)
'Then do Replace operations on strName
'...
CleanFileName = strName
Full updated CleanFileName function with Variant input:
vba
Function CleanFileName(fileName As Variant) As String
Dim arrForbidden As Variant
Dim ch As Variant
Dim strName As String
strName = CStr(fileName)
arrForbidden = Array("\", "/", ":", "*", "?", """", "<", ">", "|")
For Each ch In arrForbidden
strName = Replace(strName, ch, "_")
Next ch
CleanFileName = strName
End Function
Summary:
Change function param type to Variant.
Convert key to string explicitly before passing to function.
That fixes the ByRef mismatch error.
If you want, I can paste here the entire corrected macro for you. Just ask!
User
save as workbookname_5100 and etec?
Assistant
Sure! To save each new file as:
[ThisWorkbookName]_[Column12Value].xlsx
(e.g., if your current workbook is Report.xlsx and key is 5100, filename will be Report_5100.xlsx),
you just need to prepend the current workbook name (without extension) before the key when saving.
Here's how to do it:
Get the current workbook filename without extension:
vba
Dim wbNameOnly As String
wbNameOnly = Left(wb.Name, InStrRev(wb.Name, ".") - 1)
Sub ExportByColumn12()
Dim wb As Workbook
Dim ws As Worksheet
Dim dict As Object
Dim lastRow As Long
Dim i As Long
Dim key As Variant
Dim savePath As String
Dim newWb As Workbook
Dim headerRange As Range
Dim arr As Variant
Set wb = ThisWorkbook
Set ws = wb.Sheets(1) ' change if your data is in another sheet
' Find last used row
lastRow = ws.Cells(ws.Rows.Count, 12).End(xlUp).Row
' Get header (assuming headers in row 1)
Set headerRange = ws.Range(ws.Cells(1, 1), ws.Cells(1, 20))
' Create a dictionary to store unique values in column 12 with their row numbers
Set dict = CreateObject("Scripting.Dictionary")
' Loop through rows and collect row indexes for each unique value in column 12
For i = 2 To lastRow
key = ws.Cells(i, 12).Value
If Not dict.exists(key) Then
dict.Add key, Array(i)
Else
arr = dict(key)
ReDim Preserve arr(UBound(arr) + 1)
arr(UBound(arr)) = i
dict(key) = arr
End If
Next i
' Folder to save files - change as needed
savePath = wb.Path & "\"
If savePath = "\" Then
MsgBox "Please save the current workbook first."
Exit Sub
End If
Application.ScreenUpdating = False
' For each unique value, create new workbook and copy relevant rows
Dim rw As Variant
For Each key In dict.keys
Set newWb = Workbooks.Add
With newWb.Sheets(1)
' Copy header
headerRange.Copy .Range("A1")
' Copy rows for current key
Dim rowNums As Variant
rowNums = dict(key)
Dim destRow As Long
destRow = 2
For Each rw In rowNums
ws.Range(ws.Cells(rw, 1), ws.Cells(rw, 20)).Copy .Cells(destRow, 1)
destRow = destRow + 1
Next rw
.Columns.AutoFit
End With
' Save new workbook
On Error Resume Next
newWb.SaveAs Filename:=savePath & key & ".xlsx", FileFormat:=51 ' xlOpenXMLWorkbook = 51
If Err.Number <> 0 Then
MsgBox "Error saving file: " & savePath & key & ".xlsx"
Err.Clear
End If
On Error GoTo 0
newWb.Close SaveChanges:=False
Next key
Application.ScreenUpdating = True
MsgBox "Export completed!"
End Sub
Try this corrected version and let me know if you get any other errors!
Sub ExportByColumn12_Fast()
Dim wb As Workbook
Dim ws As Worksheet
Dim lastRow As Long
Dim savePath As String
Dim key As Variant
Dim uniqueKeys As Object
Dim rngData As Range
Dim rngFilter As Range
Dim newWb As Workbook
Dim headerRange As Range
Dim filterCol As Long
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Set wb = ThisWorkbook
Set ws = wb.Sheets(1) ' Adjust if needed
filterCol = 12
lastRow = ws.Cells(ws.Rows.Count, filterCol).End(xlUp).Row
' Check if data exist
If lastRow < 2 Then
MsgBox "No data found."
GoTo Cleanup
End If
savePath = wb.Path & "\"
If savePath = "\" Then
MsgBox "Please save the current workbook first."
GoTo Cleanup
End If
Set headerRange = ws.Range(ws.Cells(1, 1), ws.Cells(1, 20))
Set rngData = ws.Range(ws.Cells(1, 1), ws.Cells(lastRow, 20))
' Get unique keys in column 12 via dictionary
Set uniqueKeys = CreateObject("Scripting.Dictionary")
Dim arrData As Variant
Dim i As Long
arrData = ws.Range(ws.Cells(2, filterCol), ws.Cells(lastRow, filterCol)).Value
For i = 1 To UBound(arrData, 1)
key = arrData(i, 1)
If Not uniqueKeys.exists(key) Then
uniqueKeys.Add key, True
End If
Next i
' Apply autofilter and copy filtered data for each key (value in column 12)
For Each key In uniqueKeys.Keys
ws.AutoFilterMode = False
rngData.AutoFilter Field:=filterCol, Criteria1:=key
' Check if visible cells are more than header
If ws.Range(ws.Cells(2, 1), ws.Cells(lastRow, 1)).SpecialCells(xlCellTypeVisible).Count > 0 Then
Set newWb = Workbooks.Add
' Copy header
headerRange.Copy newWb.Sheets(1).Range("A1")
' Copy visible filtered rows (excluding header)
On Error Resume Next
ws.Range(ws.Cells(2, 1), ws.Cells(lastRow, 20)) _
.SpecialCells(xlCellTypeVisible).Copy _
newWb.Sheets(1).Range("A2")
On Error GoTo 0
newWb.Sheets(1).Columns.AutoFit
' Save new workbook
On Error Resume Next
newWb.SaveAs Filename:=savePath & key & ".xlsx", FileFormat:=51
If Err.Number <> 0 Then
MsgBox "Error saving file: " & savePath & key & ".xlsx"
Err.Clear
End If
On Error GoTo 0
newWb.Close SaveChanges:=False
End If
Next key
ws.AutoFilterMode = False
MsgBox "Export completed!"
Cleanup:
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
End Sub
Why is this faster?
Uses AutoFilter which is very fast for filtering rows directly on worksheet.
Copies filtered visible rows at once instead of line-by-line copying.
Copying ranges is faster than looping arrays and writing individually.
Minimizes VBA->Worksheet round trips, which are slow.
Disables screen updating and calculations during operation.
Notes:
This assumes your data has headers in row 1.
Adjust sheet name or columns if needed.
If some key contains invalid characters for filenames (e.g., / \ : * ? " < > |), the save will error — you can add code to clean filenames if needed.
You still need to save your workbook before running, so the macro can save output files in the same folder.
If you want, I can also help with:
Handling very large datasets with even bigger performance optimizations (e.g., all in memory copies).
Cleaning invalid characters from filenames.
Progress indication since processing many files might take time.
Try this and tell me how fast it is compared to your previous approach!
Sub ExportByColumn12_Fast_DynamicColumns()
Dim wb As Workbook
Dim ws As Worksheet
Dim lastRow As Long, lastCol As Long
Dim savePath As String
Dim key As Variant
Dim uniqueKeys As Object
Dim rngData As Range
Dim newWb As Workbook
Dim headerRange As Range
Dim filterCol As Long
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Set wb = ThisWorkbook
Set ws = wb.Sheets(1) ' Change if necessary
filterCol = 12 ' Column to filter by
' Determine last row & last column dynamically
lastRow = ws.Cells(ws.Rows.Count, filterCol).End(xlUp).Row
lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
' Check if data exists
If lastRow < 2 Or lastCol < 1 Then
MsgBox "No data found."
GoTo Cleanup
End If
savePath = wb.Path & "\"
If savePath = "\" Then
MsgBox "Please save the current workbook first."
GoTo Cleanup
End If
Set headerRange = ws.Range(ws.Cells(1, 1), ws.Cells(1, lastCol))
Set rngData = ws.Range(ws.Cells(1, 1), ws.Cells(lastRow, lastCol))
' Get unique keys in column 12 via dictionary
Set uniqueKeys = CreateObject("Scripting.Dictionary")
Dim arrData As Variant
Dim i As Long
arrData = ws.Range(ws.Cells(2, filterCol), ws.Cells(lastRow, filterCol)).Value
For i = 1 To UBound(arrData, 1)
key = arrData(i, 1)
If Not uniqueKeys.exists(key) Then
uniqueKeys.Add key, True
End If
Next i
' Filter and export for each key
For Each key In uniqueKeys.Keys
ws.AutoFilterMode = False
rngData.AutoFilter Field:=filterCol, Criteria1:=key
' Check if visible cells besides header are present
If ws.Range(ws.Cells(2, 1), ws.Cells(lastRow, 1)).SpecialCells(xlCellTypeVisible).Count > 0 Then
Set newWb = Workbooks.Add
' Copy header
headerRange.Copy newWb.Sheets(1).Range("A1")
On Error Resume Next
ws.Range(ws.Cells(2, 1), ws.Cells(lastRow, lastCol)) _
.SpecialCells(xlCellTypeVisible).Copy newWb.Sheets(1).Range("A2")
On Error GoTo 0
newWb.Sheets(1).Columns.AutoFit
' Save new workbook with key as filename
On Error Resume Next
newWb.SaveAs Filename:=savePath & CleanFileName(key) & ".xlsx", FileFormat:=51
If Err.Number <> 0 Then
MsgBox "Error saving file: " & savePath & key & ".xlsx"
Err.Clear
End If
On Error GoTo 0
newWb.Close SaveChanges:=False
End If
Next key
ws.AutoFilterMode = False
MsgBox "Export completed!"
Cleanup:
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
End Sub
' Optional helper function to clean invalid filename characters
Function CleanFileName(fileName As String) As String
Dim arrForbidden As Variant
Dim ch As Variant
arrForbidden = Array("\", "/", ":", "*", "?", """", "<", ">", "|")
CleanFileName = fileName
For Each ch In arrForbidden
CleanFileName = Replace(CleanFileName, ch, "_")
Next ch
End Function
What changed?
lastCol: Dynamically calculates last used column based on row 1.
Header and data ranges are from column 1 to lastCol.
The copy operation now copies all columns dynamically.
Added CleanFileName function that replaces invalid filename characters (like \ / : * ? " < > |) with underscore _ to avoid errors on saving files.
Used CleanFileName(key) when saving files.
How to use:
Paste all code in a VBA module.
Save the file (so it has a folder path to save files).
Run ExportByColumn12_Fast_DynamicColumns.
It will create files in your current workbook folder named after the distinct values in column 12.
If you want me to help with any other adjustment or explanation, just ask!
Sub ExportByColumn12_Fast_DynamicColumns()
Dim wb As Workbook
Dim wbNameOnly As String
Dim ws As Worksheet
Dim lastRow As Long, lastCol As Long
Dim savePath As String
Dim key As Variant
Dim uniqueKeys As Object
Dim rngData As Range
Dim newWb As Workbook
Dim headerRange As Range
Dim filterCol As Long
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Set wb = ThisWorkbook
wbNameOnly = Left(wb.Name, InStrRev(wb.Name, ".") - 1)
Set ws = wb.Sheets(1) ' Change if necessary
filterCol = 12 ' Column to filter by
lastRow = ws.Cells(ws.Rows.Count, filterCol).End(xlUp).Row
lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
If lastRow < 2 Or lastCol < 1 Then
MsgBox "No data found."
GoTo Cleanup
End If
savePath = wb.Path & "\"
If savePath = "\" Then
MsgBox "Please save the current workbook first."
GoTo Cleanup
End If
Set headerRange = ws.Range(ws.Cells(1, 1), ws.Cells(1, lastCol))
Set rngData = ws.Range(ws.Cells(1, 1), ws.Cells(lastRow, lastCol))
Set uniqueKeys = CreateObject("Scripting.Dictionary")
Dim arrData As Variant
Dim i As Long
arrData = ws.Range(ws.Cells(2, filterCol), ws.Cells(lastRow, filterCol)).Value
For i = 1 To UBound(arrData, 1)
key = arrData(i, 1)
If Not uniqueKeys.exists(key) Then
uniqueKeys.Add key, True
End If
Next i
Dim rw As Variant
For Each key In uniqueKeys.Keys
ws.AutoFilterMode = False
rngData.AutoFilter Field:=filterCol, Criteria1:=key
If ws.Range(ws.Cells(2, 1), ws.Cells(lastRow, 1)).SpecialCells(xlCellTypeVisible).Count > 0 Then
Set newWb = Workbooks.Add
headerRange.Copy newWb.Sheets(1).Range("A1")
On Error Resume Next
ws.Range(ws.Cells(2, 1), ws.Cells(lastRow, lastCol)).SpecialCells(xlCellTypeVisible).Copy newWb.Sheets(1).Range("A2")
On Error GoTo 0
newWb.Sheets(1).Columns.AutoFit
On Error Resume Next
newWb.SaveAs Filename:=savePath & wbNameOnly & "_" & CleanFileName(CStr(key)) & ".xlsx", FileFormat:=51
If Err.Number <> 0 Then
MsgBox "Error saving file: " & savePath & wbNameOnly & "_" & key & ".xlsx"
Err.Clear
End If
On Error GoTo 0
newWb.Close SaveChanges:=False
End If
Next key
ws.AutoFilterMode = False
MsgBox "Export completed!"
Cleanup:
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
End Sub
Function CleanFileName(fileName As Variant) As String
Dim arrForbidden As Variant
Dim ch As Variant
Dim strName As String
strName = CStr(fileName)
arrForbidden = Array("\", "/", ":", "*", "?", """", "<", ">", "|")
For Each ch In arrForbidden
strName = Replace(strName, ch, "_")
Next ch
CleanFileName = strName
End Function
Just paste this into a new VBA Module and run.
The macro will save files as:
code
[YourWorkbookName]_[Column12Value].xlsx
e.g.
Report_5100.xlsx
Report_5200.xlsx
If you want any additional customization, please ask!