Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export multiple worksheets to CSV (without saving over the current worksheet)

Tags:

csv

excel

vba

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.

like image 364
Tommy O'Dell Avatar asked Apr 26 '13 08:04

Tommy O'Dell


People also ask

Can you have multiple sheets in a CSV file?

CSV files are plain text files. Not spreadsheet files. Therefore, you can not have multiple sheets in a single CSV file.

Why does CSV only save one tab?

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...

How do I export multiple sheets in Excel?

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.


1 Answers

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.

like image 122
Kazimierz Jawor Avatar answered Nov 14 '22 23:11

Kazimierz Jawor