Fix Excel VBA SaveAs Error 1004 When Exporting a CSV
Question details
Save a copied worksheet as a CSV file in the source workbook's folder without a VBA SaveAs error.

- Product
- Microsoft Excel VBA
- Device & OS
- not provided
- Scenario
- A macro copies a worksheet to a new workbook and exports it as a CSV file in the source workbook's folder.
- Observed behavior
- The macro may raise error 1004 when it uses ActiveWorkbook.SaveAs after copying the worksheet.
Save the source workbook so it has a folder path, and check that you have permission to write to that folder. Make sure your Excel version supports the xlCSVUTF8 file format.
Save the Copied Workbook Using an Explicit Workbook Reference
Use this approach when ActiveWorkbook may no longer identify the workbook you intend to export.
Capture the source workbook and its folder before copying the worksheet. Immediately after the copy, assign the new active workbook to outputFile and use that object for SaveAs.
In Excel, open Developer > Visual Basic and locate the macro that copies and exports the worksheet.
Before the copy, assign the source workbook and folder, for example: Set sourceFile = ActiveWorkbook and destinationPath = sourceFile.Path. Immediately after sourceFile.Worksheets("Sheet1").Copy, add Set outputFile = ActiveWorkbook. Replace Sheet1 with the name of the sheet to export and declare sourceFile and outputFile as Workbook variables.
Replace ActiveWorkbook.SaveAs with: outputFile.SaveAs Filename:=destinationPath & Application.PathSeparator & myFileName, FileFormat:=xlCSVUTF8, CreateBackup:=False. Set myFileName to a valid name such as export.csv before running the command.
Run the macro from the VBA editor using Run > Run Sub/UserForm, then open the source workbook's folder and check for the CSV file.

Work With Spreadsheets and CSV Files in WPS Office
WPS Office is a free, lightweight alternative with a familiar spreadsheet interface and support for common Microsoft Office formats, making it easier to move everyday files between suites. It does not fix an Excel VBA macro error.

Frequently Asked Questions
Why can ActiveWorkbook cause a SaveAs error after a worksheet is copied?
Copying a worksheet to a new workbook changes which workbook is active. Store that new workbook with Set outputFile = ActiveWorkbook immediately after the copy, then call outputFile.SaveAs.
How do I save the CSV in the source workbook's folder?
Before copying the sheet, set destinationPath = sourceFile.Path. Use destinationPath & Application.PathSeparator & myFileName as the Filename argument to outputFile.SaveAs.
What if the source workbook has never been saved?
Its Path property will be empty. Use File > Save As to save the source workbook to a folder before running the export macro.
Does saving as CSV preserve every worksheet?
No. A CSV file contains data from one worksheet. Copy the intended worksheet to the output workbook before using SaveAs with xlCSVUTF8.




