I'm trying to create an Excel tool to split a sheet of data into multiple .csv files, to a maximum of 200 rows per csv file.
My code:
Dim CSheet As Worksheet
Dim LastRow As Long
Dim LastCol As Long
Dim currentFilePath As String
Dim filePath As String
Dim dataDate As String
Dim n As Integer
Dim r As Integer
Dim rowStartNumber As Integer
Dim rowEndNumber As Integer
Dim numOfFiles As Integer
'*****************************************************
' Declare variables
'*****************************************************
On Error Resume Next
Application.DisplayAlerts = False
Set CSheet = Worksheets("Cleaned_Data")
Worksheets("Cleaned_Data").Activate
LastRow = CSheet.Cells(Rows.Count, 1).End(xlUp).Row
LastCol = CSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Debug.Print (Application.ActiveWorkbook.Path)
currentFilePath = Application.ActiveWorkbook.Path
numOfFiles = (LastRow - 1) / 200
dataDate = Format(Worksheets("Instructions").Cells(14, 2), "DD-MMM-YYYY")
filePath = currentFilePath & "\" & dataDate
'*****************************************************
' Check if folder exists; if yes delete and recreate
'*****************************************************
'if folder does not exist
If Dir(filePath, vbDirectory) = "" Then
MkDir filePath
Else
Kill filePath & "*.*"
RmDir filePath
MkDir filePath
End If
Debug.Print ("Hello")
' Loop to create the files
For n = 1 To numOfFiles
rowStartNumber = 2 + ((n - 1) * 200)
rowEndNumber = rowStartNumber + 199
Debug.Print (rowStartNumber & " - " & rowEndNumber)
For r = rowStartNumber To rowEndNumber
Debug.Print (rowStartNumber)
'Start to get data from Csheet, up to 200 rows, and write them into a new .csv file in filePath
Next r
Next n
The loop section is what I'm struggling with. I've tried many ways of copying pasting, or going row by row to iterate and write the .csv file out. How can I do that using VBA?
' Loop to create the files
For n = 1 To numOfFiles
rowStartNumber = 2 + ((n - 1) * 200) 'first data row starts at row 2, due to headers
rowEndNumber = rowStartNumber + 199
Debug.Print (rowStartNumber & " - " & rowEndNumber)
For r = rowStartNumber To rowEndNumber
Debug.Print (rowStartNumber)
'Start to get data from Csheet, up to 200 rows, and write them into a new .csv file in filePath
Next r
Next n