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
Related
Situation: Working on an excel tool for which I need to save files as .csv on a shared folder through the below code:
Dim FileName As String
Dim Path As String
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName:= _
"FILEPATH&NAME ".txt", FileFormat:=xlText, CreateBackup:=False
Application.DisplayAlerts = True
Problem: The files created through this method are very large (20,046 Ko) and slowing down everything (saving for the user and excel queries afterwards).
This seems to stem from the fact that it's saving thousands of empty columns when my files are supposed to be only 27 columns.
What I've tried: I've tried to save as CSV instead, there's the same issue of size.
How can I code it to create a file without the empty columns and rows?
Thanks for the help!
It is not xlText, but xlCSV.
Sub test()
Dim Wb As Workbook
Dim Ws As Worksheet
Set Wb = ActiveWorkbook
Set Ws = Wb.ActiveSheet
'Wb.SaveAs Filename:="myTest.text", FileFormat:=xlCSV
Ws.SaveAs Filename:="myTest.text", FileFormat:=xlCSV
End Sub
I have a macro which creates a tab, named by a cell - every time I run the macro - this tab has different name. I have to save only this tab as a separate csv file.
For now I have the code below - it saves all 2 tabs to a specified location. I would be really grateful for any ideas how I can manage this !
Dim mySheet As Worksheet
Dim myPath As String
Application.DisplayAlerts = False
For Each mySheet In ActiveWorkbook.Worksheets
myPath = "\\F:\ABC\INPUT\"
Application.DisplayAlerts = False
ActiveWorkbook.Sheets(mySheet.Index).Copy
ActiveWorkbook.SaveAs Filename:=myPath & mySheet.Name, FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Application.DisplayAlerts = True
Next mySheet
Application.DisplayAlerts = False
In your question, you mentioned "I have a macro which creates a tab, named by a cell", so I am assuming that the tab is created based on the value in that cell. If that is the case, you may simply read the value of that cell in a vba variable. Something like:
Dim tabName as string
tabName = sheets("SheetName").range("A1").value 'if the cell for creating the sheet is A1
Now, use this variable to rename the file generated. Like,
ThisWorkbook.Worksheets(tabName).Copy
ActiveWorkbook.SaveAs Filename:="F:\path\" & tabName & ".csv"
Background:
I have two workbooks in the same directory with different sheets in each one of them.
I would like to open book2.xlsx, execute a VBA, to copy the whole content from "sheet1" in book1.xls. After this, the book1.xls should be closed automatically.
I have a code, which is moving the content next to a sheet, then I have to rename this sheet to the desired one. The problem with this is one is I the formulas in the other sheet will not work as desired. The code is as follows,
Sub XLVBACopyFiles()
Dim MonthlyWB As Variant
Dim FileName As String
FileName = ActiveWorkbook.Name
Path = ActiveWorkbook.Path & "\"
Application.DisplayAlerts = False
Application.EnableEvents = False
'Copy the sheet1 next to sheet2 in the current workbook
Application.Workbooks.Open (Path & "book1.xls")
Sheets(Array("sheet1")).Select
Sheets("sheet1").Activate
Sheets(Array("sheet1")).Move After:=Workbooks( _
FileName).Sheets("sheet2")
Application.EnableEvents = True
Application.DisplayAlerts = True
Workbooks(FileName).Save
' Workbooks(FileName).Close
End Sub
Any help with this would be highly appreciated.
If what you want , according to your comment above, is paste the content to "sheet2 itself", update the code above :
Application.Workbooks.Open (Path & "book1.xls")
Sheets(Array("sheet1")).Select
Sheets("sheet1").Activate
**Sheets(Array("sheet1")).Move After:=Workbooks( _
FileName).Sheets("sheet2")**
to
Application.Workbooks.Open (Path & "book1.xls")
Sheets(Array("sheet1")).Select
Sheets("sheet1").Activate
'Next 2 lines will select the range of content to be copied, and CTRL+C it. Edit it to your desire range
Range("A1:A5").Select
Selection.Copy
Sheets("Sheet2").Select
Range("A1").Select ' In this line you should choose which cell to start pasting
ActiveSheet.Paste
Also, to close workbook, use:
Workbooks("book1.xls").Close SaveChanges:=True
Pay attention to SaveChanges option, choose True/False if you want to save or not this workbook
I have a macro enabled workbook in my local folder. This workbook consists of 7 worksheet in total. Last sheet named as "AnsSheet".
I want to save the last sheet (AnsSheet only) in the same folder location with modified name.
Here is the code I am using which is not giving desired result.
Could you please guide?
Sheets("AnsSheet").Select
Set wb = Workbooks.Add
ThisWorkbook.Sheets("AnsSheet").Copy Before:=wb.Sheets(1)
ActiveSheet.SaveAs Filename:=ActiveWorkbook.Path & "\WF_Macro_" & Format(Date, "DD-MMM-YYYY") & ".xls"
Your Filename will be incomplete as ActiveWorkbook.Path will be blank. The ActiveWorkbook will be your newly created Workbook, and as you haven't saved it yet the Path will be empty. Use ThisWorkbook instead to get the path of the current Workbook.
I'm not sure if the ActiveSheet.SaveAs method will work but I haven't looked into it. Personally I would use the Workbook.SaveAs method to save the new Workbook. Also, instead of adding ".xls" to the end of the filename, you should specify the filetype using the FileFormat parameter MSDN FileFormat Enum
I've updated your code below with comments to help see what is going on:
Dim wb As Excel.Workbook
'\\ Create a new Workbook with only one Worksheet
Set wb = Workbooks.Add(xlWBATWorksheet)
'\\ Copy Sheet to start of new Workbook
ThisWorkbook.Sheets("AnsSheet").Copy Before:=wb.Sheets(1)
'\\ Turn off alerts and delete the unused sheet, turn alerts back on
Application.DisplayAlerts = False
wb.Sheets(2).Delete
Application.DisplayAlerts = True
'\\ Save new Workbook as a standard Workbook
wb.SaveAs Filename:=ThisWorkbook.Path & "\WF_Macro_" & Format(Date, "DD-MMM-YYYY"), _
FileFormat:=xlWorkbookNormal
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