Hi, I wonder whether someone could help me please.
Using a script I found online as a 'base' I've written the query below.
The purpose of the script takes a 'master' file and splits into smaller files saving them as a CSV.
The creation of the smaller files and copying of the data work. However I get the error: "Run-time error '1004': Method 'SaveAs' of object'_Workbook' failed" at this point:
What I'm trying to do is create save the newly created file(s) using the original filename as the part of the newly created filename then close all files.
Could some perhaps offer some guidance on where I've gone wrong?
Many thanks and kind regards
Chris
Using a script I found online as a 'base' I've written the query below.
Code:
Sub Test()
Dim wb As Workbook
Dim ThisSheet As Worksheet
Dim NumOfColumns As Integer
Dim RangeToCopy As Range
Dim RangeOfHeader As Range 'data (range) of header row
Dim WorkbookCounter As Integer
Dim RowsInFile 'how many rows (incl. header) in new files?
Dim fNameAndPath As Variant
fNameAndPath = Application.GetOpenFilename(Title:="Select File To Be Opened")
If fNameAndPath = False Then Exit Sub
Workbooks.Open Filename:=fNameAndPath
Application.ScreenUpdating = False
'Initialize data
Set ThisSheet = ActiveWorkbook.Worksheets(1)
NumOfColumns = ThisSheet.UsedRange.Columns.Count
WorkbookCounter = 1
RowsInFile = 50 'as your example, just 1000 rows per file
'Copy the data of the first row (header)
Set RangeOfHeader = ThisSheet.Range(ThisSheet.Cells(1, 1), ThisSheet.Cells(1, NumOfColumns))
For p = 2 To ThisSheet.UsedRange.Rows.Count Step RowsInFile - 1
Set wb = Workbooks.Add
'Paste the header row in new file
RangeOfHeader.Copy wb.Sheets(1).Range("A1")
'Paste the chunk of rows for this file
Set RangeToCopy = ThisSheet.Range(ThisSheet.Cells(p, 1), ThisSheet.Cells(p + RowsInFile - 2, NumOfColumns))
RangeToCopy.Copy wb.Sheets(1).Range("A2")
'Save the new workbook, and close it
Application.ScreenUpdating = False
With wb
.SaveAs Filename:=fNameAndPath & "\File " & WorkbookCounter, FileFormat:=xlCSV
wb.Close False
Application.DisplayAlerts = True
End With
'Increment file counter
WorkbookCounter = WorkbookCounter + 1
Next p
Application.ScreenUpdating = True
Set wb = Nothing
End Sub
The creation of the smaller files and copying of the data work. However I get the error: "Run-time error '1004': Method 'SaveAs' of object'_Workbook' failed" at this point:
Code:
With wb
.SaveAs Filename:=fNameAndPath & "\File " & WorkbookCounter, FileFormat:=xlCSV
wb.Close False
Application.DisplayAlerts = True
End With
What I'm trying to do is create save the newly created file(s) using the original filename as the part of the newly created filename then close all files.
Could some perhaps offer some guidance on where I've gone wrong?
Many thanks and kind regards
Chris