I'm trying to export a number of worksheets in my workbook to .csv via some code like this:
Sub Export_To_CSV(exportPath As String)
Dim filePath As String
For Each WS In ThisWorkbook.Worksheets
filePath = exportPath & "(" & WS.Name & ").dat"
WS.SaveAs Filename:=filePath, FileFormat:=xlCSV
Next
End Sub
The problem is that this saves over the current .xlsm file that I have open.
How can I get it to export the .csv without changing the name of the current file?
I thought SaveCopyAs
would do the trick, but it only applies to a workbook
and not a worksheet
.
CSV files are plain text files. Not spreadsheet files. Therefore, you can not have multiple sheets in a single CSV file.
CSV files don't store tabs. It just stores data of the tab that was opened when you exported the CSV. it's called "sheets" and csv is just a very simple text files so how can it store multiple sheets? You should save the file as a better format like xlsx, xlsb, ods...
By default, Excel will only export the active worksheet. If you have multiple worksheets and want to save all of them in the same PDF file, click Options in the Save As dialog box. The Options dialog box will appear. Select Entire workbook, then click OK.
Here comes my idea which could help you...
Add this part of code instead you current for...next
section:
'...your code here
Dim tmpWS As Worksheet
Application.DisplayAlerts = False
For Each WS In ThisWorkbook.Worksheets
filePath = exportPath & "(" & WS.Name & ").dat"
WS.Copy
Set tmpWS = ActiveSheet
tmpWS.SaveAs Filename:=filePath, FileFormat:=xlCSV
tmpWS.Parent.Close False
Next
Application.DisplayAlerts = True
'...your code here
Logic of the code? First, it makes a copy of your sheet into temporary workbook, next it saves new sheet as CSV file and finally, it closes temporary workbook. Moreover, I added Application.DisplayAlerts
instructions that your code overwrites .csv
file without asking if file already exists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With