Export to CSV without opening - excel

I am using an Excel Macro that detects two worksheets and writes them to CSV format in their current SharePoint directory. However, upon executing the macro, it proceeds to open the newly created files within the same workbook and gives me the following error:
Run-time error '1004':
Sorry, we couldn't find C:\ProgramFiles(x86)\Google\Chrome\Application...
Is it possible it was moved, renamed or deleted?
Can I perform the "Save As" without opening the new file and avoiding the given error?
To be clear, it performs the core function just fine, as the new CSV files are properly written to the Sharepoint folder, I simply want to avoid the error message.
Macro code is as below:
Sub Export()
'
' Export Macro
' Export Rules and Privileges to 'Rules.csv' and Privileges.csv'
'
' Keyboard Shortcut: Ctrl+Shift+E
'
Dim ws As Worksheet
Dim path As String
path = ActiveWorkbook.path & "\"
For Each ws In Worksheets
If ws.Name Like "Rules" Then
ws.Activate
ws.SaveAs Filename:=path & "Rules.csv", FileFormat:=xlCSV, CreateBackup:=True
End If
If ws.Name Like "Privileges" Then
ws.Activate
ws.SaveAs Filename:=path & "Privileges.csv", FileFormat:=xlCSV, CreateBackup:=True
End If
Next
Range("B9").Select
Application.Run "RulesWorkbook.xlsm!Export"
Range("B4").Select
End Sub

Thank you to FreeMan for the solution in getting rid of the error message. While I did not figure out how to prevent Excel from opening the newly generated programs, I was able to side-step that by closing the workbook upon macro execution. Updated code for the macro is below:
Sub Export()
'
' Export Macro
' Export SecurityRules and Privileges to 'Rules.csv' and 'Privileges.csv'
'
' Keyboard Shortcut: Ctrl+Shift+E
'
Dim ws As Worksheet
Dim path As String
path = ActiveWorkbook.path & "\"
For Each ws In Worksheets
If ws.Name Like "Rules" Then
ws.SaveAs Filename:=path & "Rules.csv", FileFormat:=xlCSV, CreateBackup:=True
End If
If ws.Name Like "Privileges" Then
ws.SaveAs Filename:=path & "Privileges.csv", FileFormat:=xlCSV, CreateBackup:=True
End If
Next
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub

Related

Copy a Worksheet into a new Workbook

I get a runtime error with ws.copy -> without the code works but just creates an empty workbook.
Sub SaveWorksheetAsXlsx(ws As Worksheet)
Dim filePath As String
filePath = ThisWorkbook.Path & "\" & ws.Name & ".xlsx"
' Create a new workbook
Dim newWorkbook As Workbook
Set newWorkbook = Workbooks.Add
' Copy the worksheet to the new workbook
ws.Copy 'After:=newWorkbook.Worksheets(1)
' Save the new workbook
newWorkbook.SaveAs filePath, FileFormat:=xlOpenXMLWorkbook
newWorkbook.Close SaveChanges:=False
End Sub
Copy Sheet to a New Workbook
If you replace As Worksheet with As Object, the procedure will also work for charts.
To reference the last opened workbook, you can safely use Workbook(Workbooks.Count).
Turn off Application.DisplayAlerts to overwrite without confirmation. If you don't do this, when the file exists, you'll be asked to save it. If you select No or Cancel, the following error will occur:
Run-time error '1004': Method 'SaveAs' of object '_Workbook' failed
If your intent is to reference the sheet's workbook, you can use the .Parent property. Then the procedure will not be restricted just to the workbook containing this code (ThisWorkbook). Otherwise, replace Sheet.Parent with ThisWorkbook.
If you instead of the backslash (\) use Application.PathSeparator, the procedure will also work on computers with a different operating system than Windows.
For a new workbook, the default type is .xlsx so you don't need to specify the file extension or format.
Sub SaveSheetAsXlsx(ByVal Sheet As Object)
' Copy the sheet to a new single-sheet workbook.
Sheet.Copy
' Reference, save and close the new workbook.
Dim nwb As Workbook: Set nwb = Workbooks(Workbooks.Count)
Application.DisplayAlerts = False ' overwrite without confirmation
nwb.SaveAs Sheet.Parent.Path & Application.PathSeparator & Sheet.Name
Application.DisplayAlerts = True
nwb.Close False
End Sub
set newWorkbook = workbooks.Add creates a new workbook. But ws.Copy without arguments copies ws to a new workbook. Now you have two new workbooks which is clearly not what you intend. MS learning documents gives an example of how to do copy a worksheet in its documentation on the copy command. Reference: https://learn.microsoft.com/en-us/office/vba/api/excel.worksheet.copy
Sub foo()
Call SaveWorksheetAsXlsx(Worksheets("Sheet3"))
End Sub
Sub SaveWorksheetAsXlsx(ws As Worksheet)
Dim filePath As String
filePath = ThisWorkbook.Path & "\" & ws.Name & ".xlsx"
If Not CreateObject("Scripting.FileSystemObject").FileExists(filePath) Then
ws.Copy
ActiveWorkbook.SaveAs filePath, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close SaveChanges:=False
Else
MsgBox "Error: unable to save file. File already exists: " + filePath
End If
End Sub
This obviously relies on the expected behavior that when you copy a worksheet to a new workbook that workbook becomes the active workbook. I have used this before without any problems (for many years I guess), although it does make me a little nervous relying on default behaviors. So you may consider adding some guard clauses, perhaps only saving the workbook if it has an empty path (i.e., ensure it is a newly added workbook -> if ActiveWorkbook.Path = "". So, coding prophylacticly and very cautiously:
Sub foo()
Call SaveWorksheetAsXlsx(Worksheets("Sheet3"))
End Sub
Sub SaveWorksheetAsXlsx(ws As Worksheet)
Dim filePath As String
filePath = ThisWorkbook.Path & "\" & ws.Name & ".xlsx"
If Not CreateObject("Scripting.FileSystemObject").FileExists(filePath) Then
ws.Copy
If ActiveWorkbook.Path = "" Then 'Extra check to ensure this is a newly created and unsaved workbook
ActiveWorkbook.SaveAs filePath, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close SaveChanges:=False
Else
MsgBox "Unexpected error attempting to save file " + filePath
End If
Else
MsgBox "Error: unable to save file. File already exists: " + filePath
End If
End Sub

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

Turning PDF Macro into Excel

I am trying to convert this code that instead of saving PDF copies it saves the individual sheets as Excel workbooks instead. I have tried changing the Export as fixed format to xlsm but it appears to have a run time error. Very new to this but any help would be appreciated.
Sub PDF()
Dim xWs As Worksheet
Application.ScreenUpdating = False
For Each xWs In ThisWorkbook.Worksheets
If xWs.Visible = True Then
If xWs.Name <> "HOME" And xWs.Name <> "DATA" Then
xWs.Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "\PDF P&L\" & Range("G1").Value & ".pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=False, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End If
End If
Next xWs
Application.ScreenUpdating = False
End Sub
The .ExportAsFixedFormat method doesn't support export to excel file formats as per the documentation
The action you're most likely looking for is .move. When not specified with where to move, this will create a new workbook with the moved sheet. You can then use workbooks(Workbooks.count) to access the latest created workbook. See example code below:
Dim wb As Workbook
ActiveSheet.Move
Set wb = Workbooks(Workbooks.Count)
wb.SaveAs Filename:="yournamehere", FileFormat:=xlOpenXMLWorkbookMacroEnabled 'etc...
Please note, when this is done to the last remaining or only sheet in the workbook, this will throw an error. For more info on the .move method, see the link. For file formats to use see here.
Also, when moving a sheet, all the VBA code on the worksheet will be pulled across, but the modules related to the workbook won't. So attempting to save it as anything but xlsm when it has any code on it will result in a prompt or error.

How to save the file that is being opened?

I have a macro that works for one particular file.
How can I make it work for all my files? Specifically how do I change the name of the file so that it saves the file that is being opened?
Sub Macro1()
'
' Macro1 Macro
'
' Keyboard Shortcut: Ctrl+m
'
Range("A:A,B:B").Select
Range("B1").Activate
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlLineStacked
ActiveChart.SetSourceData Source:=Range( _
"'cwapp5_MemCPU-Date-Mem'!$A:$A,'cwapp5_MemCPU-Date-Mem'!$B:$B")
ChDir "D:\WayneCSV"
ActiveWorkbook.SaveAs Filename:="D:\WayneCSV\cwapp5_MemCPU-Date-Mem.xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
End Sub
With ActiveSheet.Shapes.AddChart
.ChartType = xlLineStacked
.SetSourceData Source:=Range( _
"'cwapp5_MemCPU-Date-Mem'!$A:$A,'cwapp5_MemCPU-Date-Mem'!$B:$B")
End With
ChDir "D:\WayneCSV"
ActiveWorkbook.SaveAs Filename:="D:\WayneCSV\" & *YourFileNameHere* &".xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Replace the YourFileNameHere with the name you'd like to save the file with.
Or if you want to simply save the active workbook with the change
ActiveWorkbook.SaveAs Filename:=ThisWorkbook.FullName, _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
If you want to loop through all possible workbook or file inside of "D:\WayneCSV" just tell me what you mean by make it work for all my files? weather that means open excel sheets, or workbook, or all files with extension of *.xlsx inside of "D:\WayneCSV"
Edit:
Dim StrFile As String
StrFile = Dir("D:\WayneCSV\*.CSV") ' Looks up each file with CSV extension
Do While Len(StrFile) > 0 ' While the file name is greater then nothing
Workbooks.Open Filename:= "D:\WayneCSV\" & StrFile ' Open current workbook
ActiveSheet.Shapes.AddChart.Select ' Add a chart
ActiveChart.ChartType = xlLineStacked ' Add a chart type
ActiveChart.SetSourceData Source:=Range("$A1:$B1", Range("$A1:$B1").End(xlDown)) ' Set the source range to be the used cells in A:B on the open worksheet
With ActiveChart.Parent
.Height = .Height*1.5 'Increase Height by 50%
.Width = .Width*1.5 'Increase Width by 50%
End With
'Note the setting of the source will only work while there are no skipped blank if you
'have empty rows in the source data please tell me and i can provide you with another
' way to get the information
ActiveWorkbook.SaveAs Filename:="D:\WayneCSV\" & StrFile & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False ' Save file as excel xlsx with current files name
ActiveWorkbook.Close ' Close when finished before opening next file this can be removed if you'd like to keep all open for review at the end of loop.
StrFile = Dir ' Next File in Dir
Loop
Let me know if it works as I can't test without your folders and data. But it should work.
Check out this SO link
I think what you want to do is replace :="D:\WayneCSV\cwapp5_MemCPU-Date-Mem.xlsx"
with ActiveWorkbook.FullName in ActiveWorkbook.SaveAs line
where it is written
Filename:="D:\WayneCSV\cwapp5_MemCPU-Date-Mem.xlsx"
that's your filename you could replace it with ThisWorkbook.FullName it should work
So it should give you something like this.
Filename:=ThisWorkbook.FullName,
Also I don't understand that part
ChDir "D:\WayneCSV"
Why put the path then the full name
I'm more an access programmer than an excel one so I could be wrong.
Your macro, from what I can tell, is adding a chart based off of some data and saving the sheet.
That is a very specialized Macro, but you would need to change the directory as others listed to a directory on your local drive but you also need to find out where the data you are creating a chart for is being stored.
Sub Macro1()
' ' Macro1 Macro ' ' Keyboard Shortcut: Ctrl+m ' '<<< This is the naming convention and hotkey if you goto Tools > Macros in Excel 2003 or Developer > Macros in 2010
'Range("A:A,B:B").Select '<<< This is where you are selecting all data in columns A and B and is not needed so I commented it out
'Range("B1").Activate '<<< This code is 'activating' a cell, but not sure why, so I commented it out as it should not be needed
ActiveSheet.Shapes.AddChart.Select '<<< You are adding a chart here
ActiveChart.ChartType = xlLineStacked '<<<Defining a chart type
ActiveChart.SetSourceData Source:=Range( _ "'cwapp5_MemCPU-Date-Mem'!$A:$A,'cwapp5_MemCPU-Date-Mem'!$B:$B") '<<< Setting it's source data from a worksheet called 'cwapp5_MemCPU-Date-Mem' with header information from Column B and Data from Column A
ChDir "D:\WayneCSV"
ActiveWorkbook.SaveAs Filename:="D:\WayneCSV\cwapp5_MemCPU-Date-Mem.xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False '<<< You are saving a copy of your workbook
End Sub
To make this work for other workbooks you need to rename all of the ranges to where your data is, rename the tabs to what you have your tabs named, and rename the WorkBook to what you want it saved as and where.

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