Open DevCEDTeam opened 1 year ago
To create a VBA macro in Excel that splits a table into 2,000-row tab sections in a sequential series and exports them as .csv files, you can follow these steps:
Press ALT
+ F11
to open the VBA editor in Excel.
Insert a new module by clicking "Insert" > "Module."
Paste the following VBA code into the module:
Sub SplitAndExportCSV()
Dim ws As Worksheet
Dim lastRow As Long
Dim chunkSize As Long
Dim i As Long
Dim fileNumber As Integer
Dim fileName As String
Dim startRow As Long
' Set the worksheet containing your data
Set ws = ThisWorkbook.Sheets("Sheet1") ' Replace "Sheet1" with your sheet name
' Determine the last row in the worksheet
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
' Set the chunk size (2,000 rows)
chunkSize = 2000
' Initialize file number and start row
fileNumber = 1
startRow = 2 ' Start from row 2 (assuming headers in row 1)
' Loop through the data and export chunks to CSV files
Do While startRow <= lastRow
' Create a new CSV file
fileName = "Chunk_" & fileNumber & ".csv"
Open fileName For Output As #fileNumber
' Write headers to the CSV file
For j = 1 To ws.UsedRange.Columns.Count
Print #fileNumber, ws.Cells(1, j).Value
Next j
' Write data rows to the CSV file
For i = startRow To startRow + chunkSize - 1
If i <= lastRow Then
For j = 1 To ws.UsedRange.Columns.Count
Print #fileNumber, ws.Cells(i, j).Value
Next j
End If
Next i
' Close the CSV file
Close #fileNumber
' Increment file number and start row
fileNumber = fileNumber + 1
startRow = startRow + chunkSize
Loop
End Sub
Make sure to replace "Sheet1"
with the name of your worksheet containing the data.
Close the VBA editor.
To run the macro, press ALT
+ F8
to open the "Macro" dialog box. Select the "SplitAndExportCSV" macro and click "Run."
This VBA macro will split your data into 2,000-row chunks and export them as CSV files (e.g., Chunk_1.csv, Chunk_2.csv, etc.). Each file will contain the same headers from the original data, making them suitable for your data analysis or other purposes.
Split Voter Register List < 2k