I've created a macro to export several tabs of a spreadsheet to csv files, then reopen the original document. Normally the macro runs correctly, however when run through a button it fails to find other sheets in the workbook.
The document contains 5 tabs: 1 for the button, and 4 for the data (hardcoded below). When I run the macro, it exports the 4 sheets correctly but when I press the button, it exports the first sheet 4 times (the one containing the button, not listed in the macro). All I can think is that the button is failing to pass the active workbook to the macro, and therefore it cannot "see" the Worksheets object...is there something I can do to fix this?
Note that all lines other than the SaveAs commands are (theoretically) unrelated. I have tried replacing "Worksheets" with "ActiveWorkbook.Worksheets" and gotten the same result.
Sub SaveAsCSVs()
Dim fullname As String
fullname = ThisWorkbook.fullname
Application.DisplayAlerts = False
Worksheets("Ships").SaveAs Filename:=ThisWorkbook.path & "\ships", FileFormat:=xlCSV
Worksheets("Weapons").SaveAs Filename:=ThisWorkbook.path & "\weapons", FileFormat:=xlCSV
Worksheets("Specials").SaveAs Filename:=ThisWorkbook.path & "\specials", FileFormat:=xlCSV
Worksheets("Modifiers").SaveAs Filename:=ThisWorkbook.path & "\modifiers", FileFormat:=xlCSV
Application.Workbooks.Open (fullname)
Application.DisplayAlerts = True
Workbooks("modifiers.csv").Close
End Sub
Strange, behavior, indeed...
Being a single sheet to be saved, please use the next adapted code. It should work in both cases:
Sub SaveAsCSVs()
Dim fullname As String
fullname = ThisWorkbook.fullname
Application.DisplayAlerts = False
Worksheets("Ships").Copy 'it creates a new workbook containing only the copied sheet...
ActiveWorkbook.saveas FileName:=ThisWorkbook.Path & "\ships", FileFormat:=xlCSV
ActiveWorkbook.Close False
Worksheets("Weapons").Copy
ActiveWorkbook.saveas FileName:=ThisWorkbook.Path & "\weapons", FileFormat:=xlCSV
ActiveWorkbook.Close False
Worksheets("Specials").Copy
ActiveWorkbook.saveas FileName:=ThisWorkbook.Path & "\specials", FileFormat:=xlCSV
ActiveWorkbook.Close False
Worksheets("Modifiers").Copy
ActiveWorkbook.saveas FileName:=ThisWorkbook.Path & "\modifiers", FileFormat:=xlCSV
ActiveWorkbook.Close False
'Application.Workbooks.Open (fullname) 'no need to open, it remained opened...
Application.DisplayAlerts = True
End Sub
Related
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
I have some code that will copy a sheet and then create a new workbook and then paste it and adjust the sheet name and workbook name before saving it to the Desktop.
All the called subs do is transpose ranges of data from the entry sheet to the export sheet which is the one that is copied (named "Rows") to be pasted into the new workbook.
Code is used as a button and so far no declaration has been required.
Sub UploadSheet()
Call TransposeHS
Call TransposeOrigin
Call TransposeValues
Application.ScreenUpdating = False
Path = CreateObject("WScript.Shell").specialfolders("Desktop")
Worksheets("Rows").Cells.Copy
Workbooks.Add (xlWBATWorksheet)
ActiveWorkbook.ActiveSheet.Paste
ActiveWorkbook.ActiveSheet.Name = "Rows"
ActiveWorkbook.SaveAs Filename:=Path & "\" & "Upload" & ".xlsx"
ActiveWorkbook.Close SaveChanges:=True
Application.ScreenUpdating = True
MsgBox "Exported to Desktop"
End Sub
How do I adjust the code to copy over 2 sheets instead of just the one into a new workbook?
Creating a new workbook with Workbooks.Add and then pasting is overcomplicated.
Call Copy on the worksheet(s) without specifying any parameters; a new workbook is created with the copied sheet(s), and is the ActiveWorkbook.
Worksheets(Array("Rows", "SecondSheet")).Copy
ActiveWorkbook.SaveAs Filename:=Path & "\" & "Upload" & ".xlsx"
Below is my code for saving the file without the VBA codes.
It saves together with the VBA codes.
Sheets.Select
Cells.Copy
Cells.PasteSpecial xlPasteValues
Application.DisplayAlerts = False
ThisWorkbook.SaveAs "C:\Users\sgffa\Desktop\Profile_Macros\NEW\" & NFolder & "\" & "C",
FileFormat:=xlExcel8
Application.DisplayAlerts = True
Next x
End Sub
Save your project as xlsx instead of xlsm then the Code shouln'd be saved
you could first copy sheets in a new workbook and then save it
Sheets.Copy
Sheets.Select
Cells.Copy
Cells.PasteSpecial xlPasteValues
Application.CutCopyMode = False
With ActiveWorkbook
Application.DisplayAlerts = False
.SaveAs "C:\Users\sgffa\Desktop\Profile_Macros\NEW\" & NFolder & "\" & "C.xlsx"
Application.DisplayAlerts = True
.Close True
End With
from
ThisWorkbook.SaveAs "C:\Users\sgffa\Desktop\Profile_Macros\NEW\" & NFolder & "\" & "C", FileFormat:=xlExcel8
to this:
ThisWorkbook.SaveAs "C:\Users\sgffa\Desktop\Profile_Macros\NEW\" & NFolder & "\" & "C" & ".xlsx", FileFormat:=xlOpenXMLWorkbook
SaveAs Confusion
I'm confused, too. As it happens, when you save your macro enabled workbook (.xlsm) as macro not-enabled workbook (.xlsx), the workbook stays open still having the code in it. But the good thing is that it is saved without code. You can now save it, 'manually' SaveAs it, it will still be without code (macros) the next time you open it.
The code should demonstrate the following:
It is good practice to start with Option Explicit which will help
you by alerting you when something is wrong.
It is good practice to use constants at the beginning of the code,
especially for such long file paths, so when you have to change them
you can easily find them.
When you disable an event, there is a possibility you won't be able
to enable it again if you're not careful. If an error occurs, you should redirect
the code to enable those events again.
If you want to close the workbook, then use the line ThisWorkbook.Close
Option Explicit
Sub SaveMacroDisabled()
Const strPath = "I:\Excel\MyDocuments\Test\Test4\"
Const strXLSX = "BookMacroDisabled"
On Error GoTo ProgramError
Application.DisplayAlerts = False
ThisWorkbook.SaveAs strXLSX, _
FileFormat:=xlWorkbookDefault
SafeExit:
Application.DisplayAlerts = True
' ThisWorkbook.Close
Exit Sub
ProgramError:
MsgBox "An unexpected error occurred"
On Error GoTo 0
GoTo SafeExit
End Sub
I wrote a basic macro (very new to VBA) that extracts two columns from a workbook and puts them into a new workbook which I name and save. This works fine, but when I run it it opens and saves one as intended (e.g. "Health Care Portfolio") and opens (but doesn't name/save) a second blank book (with the standard "Book #" name). An excerpt of my code is below, could someone point out why this is happening? Thank you
Sub CreateHealthcare()
Sheets("Health Care").Select
With Application
.SheetsInNewWorkbook = 1
.Workbooks.Add
With Workbooks.Add
Workbooks("TVL Portfolio Creator.xlsm").Sheets("Health Care").Range("D:D").Copy
.Sheets(1).Range("A1").PasteSpecial Paste:=xlPasteValues
Workbooks("TVL Portfolio Creator.xlsm").Sheets("Health Care").Range("E:E").Copy
.Sheets(1).Range("B1").PasteSpecial Paste:=xlPasteValues
.Sheets(1).Name = "Health Care Portfolio"
End With
ActiveWorkbook.SaveAs Filename:="C:\Users\example\Health Care Portfolio" & Format(Now(), " DDMMMYY") _
, FileFormat:=xlCSV, CreateBackup:=False
End With
End Sub
It seems to me your intention is for only 1 new workbook to be created and saved.
Your code contains the workbooks.add statement twice.
So taking the first out, should solve your problem.
If that doesn't work, I would recommend declaring a Workbook object, and referencing that.
Also the line Sheets("Health Care").Select doesn't really do anything since your copy-statements include an explicit reference.
Your code would look something like this:
Sub CreateHealthcare()
Dim NewBook as Workbook
Application.SheetsInNewWorkbook = 1
Set NewBook = Workbooks.Add
With NewBook
Workbooks("TVL Portfolio Creator.xlsm").Sheets("Health Care").Range("D:D").Copy
.Sheets(1).Range("A1").PasteSpecial Paste:=xlPasteValues
Workbooks("TVL Portfolio Creator.xlsm").Sheets("Health Care").Range("E:E").Copy
.Sheets(1).Range("B1").PasteSpecial Paste:=xlPasteValues
.Sheets(1).Name = "Health Care Portfolio"
End With
NewBook.SaveAs Filename:="C:\Users\example\Health Care Portfolio" & Format(Now(), " DDMMMYY") _
, FileFormat:=xlCSV, CreateBackup:=False
End With
End Sub
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