Export more sheets as separate .csv files - excel

I'm trying to export two sheet in two different csv file using the code presented below:
import_bt.SaveAs Filename:="D:\Temp\import_bt.csv", FileFormat:=xlCSV, CreateBackup:=False, Local:=False
import_brd.SaveAs Filename:="D:\Temp\import_brd.csv", FileFormat:=xlCSV, CreateBackup:=False, Local:=True
The code works fine but I've an issue, it saves also my entire file as the last .csv file named import_brd.

In order to be able to copy sheets, without changing the active document name, you cannot proceed as you tried. It will always save the sheet, but the workbook will be Saved As your last allocated (csv) name.
Try this code, please:
Sub testSaveSheetAsCSV()
Dim import_bt As Worksheet, import_brd As Worksheet, wb As Workbook
'I used dummy sheets name only for testing reason. Please, use your real ones:
Set import_bt = Sheets("Test") 'use here your necessary sheet
Set import_brd = Sheets("Teste") 'use here your necessary sheet
Set wb = Workbooks.aDD
import_bt.Copy Before:=wb.Worksheets(1)
wb.SaveAs fileName:=ThisWorkbook.path & "\import_bt.csv", FileFormat:=xlCSV, CreateBackup:=False, Local:=False
import_brd.Copy Before:=wb.Worksheets(1) 'it will save its first sheet
wb.SaveAs fileName:=ThisWorkbook.path & "\import_brd.csv", FileFormat:=xlCSV, CreateBackup:=False, Local:=True
wb.Close False
End Sub
It adds a new workbook, copy the sheet necessary to be transformed in CSV, before the existing first one of the newly created workbook and save it (AS CSV) after that. It repeats the steps for the second sheet and closes the temporary workbook.
If you need to avoid the warning regarding overwriting of the existing file(s) (if the case), the code can be adapted to avoid it. Only in case you want playing with the code, or updating the existing csv files with the last necessary ones.

Related

Convert .xlsm to .csv [duplicate]

I appreciate there are lots of entries like save individual excel sheets as csv
and Export each sheet to a separate csv file - But I want to save a single worksheet in a workbook.
My code in my xlsm file has a params and data sheet. I create a worksheet copy of the data with pasted values and then want to save it as csv. Currently my whole workbook changes name and becomes a csv.
How do I "save as csv" a single sheet in an Excel workbook?
Is there a Worksheet.SaveAs or do I have to move my data sheet to another workbook and save it that way?
CODE SAMPLE
' [Sample so some DIMs and parameters passed in left out]
Dim s1 as Worksheet
Dim s2 as Worksheet
Set s1 = ThisWorkbook.Sheets(strSourceSheet)
' copy across
s1.Range(s1.Cells(1, 1), s1.Cells(lastrow, lastcol)).Copy
' Create new empty worksheet for holding values
Set s2 = Worksheets.Add
s2.Range("A1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats
' save sheet
s2.Activate
strFullname = strPath & strFilename
' >>> BIT THAT NEEDS FIXIN'
s2.SaveAs Filename:=strFullname, _
FileFormat:=xlCSV, CreateBackup:=True
' Can I do Worksheets.SaveAs?
Using Windows 10 and Office 365
This code works fine for me.
Sub test()
Application.DisplayAlerts = False
ThisWorkbook.Sheets(strSourceSheet).Copy
ActiveWorkbook.SaveAs Filename:=strFullname, FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
It's making a copy of the entire strSourceSheet sheet, which opens a new workbook, which we can then save as a .csv file, then it closes the newly saved .csv file, not messing up file name on your original file.
This is fairly generic
Sub WriteCSVs()
Dim mySheet As Worksheet
Dim myPath As String
'Application.DisplayAlerts = False
For Each mySheet In ActiveWorkbook.Worksheets
myPath = "\\myserver\myfolder\"
ActiveWorkbook.Sheets(mySheet.Index).Copy
ActiveWorkbook.SaveAs Filename:=myPath & mySheet.Name, FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Next mySheet
'Application.DisplayAlerts = True
End Sub
You just need to save the workbook as a CSV file.
Excel will pop up a dialog warning that you are saving to a single sheet, but you can suppress the warning with Application.DisplayAlerts = False.
Don't forget to put it back to true though.
Coming to this question several years later, I have found a method that works much better for myself. This is because the worksheet(s) I'm trying to save are large and full of calculations, and they take an inconvenient amount of time to copy to a new sheet.
In order to speed up the process, it saves the current worksheet and then simply reopens it, closing the unwanted .csv window:
Sub SaveThisSheetInParticular()
Dim path As String
path = ThisWorkbook.FullName
Application.DisplayAlerts = False
Worksheets("<Sheet Name>").SaveAs Filename:=ThisWorkbook.path & "\<File Name>", FileFormat:=xlCSV
Application.Workbooks.Open (path)
Application.DisplayAlerts = True
Workbooks("<File Name>.csv").Close
End Sub
Here the Sheet and csv filename are hardcoded, since nobody but the macro creator (me) should be messing with them. However, it could just as easily be changed to store and use the Active Sheet name in order to export the current sheet whenever the macro is called.
Note that you can do this with multiple sheets, you simply have to use the last filename in the close statement:
Worksheets("<Sheet 1>").SaveAs Filename:=ThisWorkbook.path & "\<File 1>", FileFormat:=xlCSV
Worksheets("<Sheet 2>").SaveAs Filename:=ThisWorkbook.path & "\<File 2>", FileFormat:=xlCSV
[...]
Workbooks("<File 2>.csv").Close

Save Copy as CSV MSDOS (Without closing/changing workbooks)

I have a macro that saves the current workbook as CSV MSDOS format.
Here's my code:
Sub Save_CSV()
Dim Location, FileName As String
Location = "C:\Users\myawesomename\OneDrive\Desktop\GM MRP\"
FileName = Left(ActiveWorkbook.name, Len(ActiveWorkbook.name) - 5)
ActiveWorkbook.SaveAs FileName:= _
Location & FileName & ".csv", FileFormat:= _
xlCSVMSDOS, CreateBackup:=False
ActiveWorkbook.Save
End Sub
After I use this macro, I'm no longer working on the xlsv. Rather, I'm working on the CSV version with all the sheets still present. If I close the workbook without saving it, I can then open the CSV file and only the first sheet is present. It's fine that only the first sheet is present but I want it to save a separate CSV file (with the first sheet only present) while continuing to work on the XLSX file without opening the CSV at all. I'm not trying to save each sheet as a separate file.
I tried several things including changing "Activeworkbook.SaveAs" to "Activeworkbook.savecopyas" but I couldn't achieve the desired result.
Thank you,

Open and Save a New Workbook as CSV file (delimited)

I have a workbook that has about 30 sheets. Each sheet has it's own macro. Then, a sheet called "Main Page has macros. One of them Merges all sheets, creating a new sheet combined. I need another macro that when clicked, opens a NEW workbook, copies data from Sheet "Combined" and saves it as it's own Workbook, and also, name it "Tracking Import File (todays date) .CSV" (delimited) I can get it to do all of that except the Format of the CSV file is not the same as when I manually do it. Currently i have this macro doing this for another sheet as well, but that sheet gets saved as a normal workbook extension, which is working just fine. This is the code I have right now:
Set wb = Workbooks.Add
ThisWorkbook.Sheets("Back Order Follow up Report").Copy Before:=wb.Sheets(1)
wb.SAVEAS "S:\Production Department\Backorder Follow up reports\Back Order Follow up Report." & Format(Date, "MM.DD.YY") & ".xlsx"
*Set wb = Workbooks.Add
ThisWorkbook.Sheets("Combined").Copy Before:=wb.Sheets(1)
wb.SAVEAS "S:\Production Department\Tracking import\Tracking Import FileTEST." & Format(Date, "MM.DD.YY") & ".csv"*
End Sub
There is a second, optional parameter on the wb.SaveAs method that tells Excel what format to save the file in. Merely putting ".csv" at the end of a file doesn't make it a CSV, that's only a name. To save as a CSV use:
wb.SAVEAS "S:\Production Department\Tracking import\Tracking Import FileTEST." & Format(Date, "MM.DD.YY") & ".csv", xlCSV

Macro to export worksheets in .xlsx workbooks to tab-delimited .txt files won't work with .xlsm workbooks

Edit: I updated my code based on the comments, but get the same symptoms.
Edit 2: I updated the code, again, and I know that it works on a directory of .xlsx files. If I convert all of the .xlsm files to .xlsx files to drop the macros/code, then the code works great. Likely this problem is too localized.
Earlier today I learned how to loop over a folder of .xlsx files and export every sheet to a tab-delimited .txt file. My bigger goal is to loop over a folder of .xlsm files (whose macros aren't all on my machine) and write the data worksheets to .txt files.
Here's the modified code.
Sub exportsSheetsToTextForAll()
Application.AutomationSecurity = msoAutomationSecurityForceDisable
excelFiles = Dir(ThisWorkbook.Path & "\" & "Payout data*.xlsm")
fromPath = ThisWorkbook.Path
Do While Len(excelFiles) > 0
Debug.Print Files
Set oWb = Workbooks.Open(Filename:=fromPath & "\" & excelFiles)
Application.Run "exportSheetsToText", oWb
oWb.Close SaveChanges:=False
excelFiles = Dir
Loop
End Sub
Sub exportSheetsToText(iWb As Workbook)
For Each ws In iWb.Worksheets
ws.Copy
Set wb = ActiveWorkbook
textFile = Left(iWb.FullName, InStr(iWb.FullName, ".") - 1) & "-" & ws.Name & ".txt"
wb.SaveAs Filename:=textFile, FileFormat:=xlText
wb.Close SaveChanges:=False
Next ws
End Sub
I modified the answer to my first question due to the structure of the .xlsm files. Each .xlsm file has a data query worksheet ("REQUEST_TABLE") with cells for query entries and buttons for macros. Running the query generates new sheets ("Sheet1", "Sheet2", etc) with the data I want to export.
When I run the exportAllSheetsToText() macro it opens the first worksheet, but it starts with the data query worksheet ("REQUEST_TABLE"), saves it to a tab-delimited text file, and stops rather than proceeding through all of the worksheets. I thought that the macro would carry on through all of the sheets as is does with my original macro for looping over all workbooks and worksheets in a directory.
What changes when I run my macro on an .xlsm file? Do I need to strip these worksheets to their own .xlsx files first? Thanks!

Why does VBA ActiveWorkbook.SaveAs change the open spreadsheet?

My function is as follows:
Sub saveCSV()
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:= _
"c:\temp\file.csv", FileFormat:=xlCSV _
, CreateBackup:=False
End Sub
I'm trying to export the active worksheet to CSV. When I run the code in the title, Book1.xlsm changes to file.csv and Sheet1 changes to file. The export works fine. How can I do the export without these unwanted side effects?
That's always how SaveAs has worked. The only way to get around this is to copy the worksheet and do a SaveAs on the copy, then close it.
EDIT: I should add an example as it's not that difficult to do. Here's a quick example that copies the ActiveSheet to a new workbook.
Dim wbk As Workbook
Set wbk = Workbooks.Add
ActiveSheet.Copy wbk.Sheets(1) ' Copy activesheet before the first sheet of wbk
wbk.SaveAs ....
wbk.Close
A complicated workbook may get issues with links and macros, but in ordinary scenarios this is safe.
EDIT 2: I'm aware of what you're trying to do, as your other question was about trying to trigger an export on every change to the sheet. This copy sheet approach presented here is likely to be highly disruptive.
My suggestion is to write a CSV file by hand to minimise GUI interruption. The sheet is likely to become unusable if the saves are occurring at high frequency. I wouldn't lay the blame for this at the door of Excel, it simply wasn't built for rapid saves done behind the scenes.
Here's a little routine that does what you want by operating on a copy of the original ... copy made via file scripting object. Hardcoded to operate on "ThisWorkbook" as opposed to active workbook & presumes ".xlsm" suffix - could tweak this to do the job I think:
Public Sub SaveCopyAsCsv()
Dim sThisFile As String: sThisFile = ThisWorkbook.FullName
Dim sCsvFile As String: sTempFile = Replace(sThisFile, ".xlsm", "_TEMP.xlsm")
ThisWorkbook.Save ' save the current workbook
' copy the saved workbook ABC.xlsm to TEMP_ABC.xlsm
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Call fso.deletefile(sTempFile, True) ' deletes prev temp file if it exists
On Error GoTo 0
Call fso.CopyFile(sThisFile, sTempFile, True)
' open the temp file & save as CSV
Dim wbTemp As Workbook
Set wbTemp = Workbooks.Open(sTempFile) ' open the temp file in excel
' your prev code to save as CSV
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName:="c:\temp\file.csv", FileFormat:=xlCSV, CreateBackup:=False
wbTemp.Close ' close the temp file now that the copy has been made
Application.DisplayAlerts = True
' delete the temp file (if you want)
On Error Resume Next
Call fso.deletefile(sTempFile, True) ' deletes the temp file
On Error GoTo 0
End Sub

Resources