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
Related
Wrote some code below to help me save some time saving files, the below is the shorter version which only saves one worksheet.
Sometimes it works perfectly, but most of the time it just silently crashes Excel with no error warning.
Nothing wrong while debugging... Not sure if ThisWorkbook.Sheets might be causing the issue?
Sub Save_CPC()
'Define the sheets to copy
Dim sheetsToCopy As Variant
sheetsToCopy = Array("RWF CPC")
'Create a new workbook
Dim newWorkbook As Workbook
Set newWorkbook = Workbooks.Add
'Loop through the sheets to copy
For i = 0 To UBound(sheetsToCopy)
'Copy the sheet to the new workbook
ThisWorkbook.Sheets(sheetsToCopy(i)).Copy Before:=newWorkbook.Sheets(1)
Next i
'Break links in the new workbook
newWorkbook.BreakLink Name:=ThisWorkbook.Name, Type:=xlExcelLinks
'Hide the sheet Sheet1 in new workbook
newWorkbook.Sheets("Sheet1").Visible = False
'Save the new workbook in the original folder
Dim saveName As String
saveName = ThisWorkbook.Sheets("Macros").Range("B13").Value
newWorkbook.SaveAs ThisWorkbook.Path & "\" & saveName & ".xlsx"
End Sub
Thanks in advance!!
Should copy and save worksheet as new spreadsheet with given name in current folder.
Copy Worksheets To a New Workbook
In One Go
Note that you can copy all the worksheets in one go as suggested by BigBen in the comments:
ThisWorkbook.Sheets(sheetsToCopy).Copy
Dim NewWorkbook As Workbook: Set NewWorkbook = Workbooks(Workbooks.Count)
The major drawback is that the worksheets in the new workbook will appear in the order they are appearing in the old workbook which may not necessarily be the order they are appearing in the array.
Additionally, at least one of the worksheets needs to be visible, and very hidden worksheets will not be copied.
Loop
Option Explicit
Sub SaveCPC()
' Start error-handling routine.
On Error GoTo ClearError
' Populate an array with the names of the worksheets to copy.
Dim sheetsToCopy() As Variant: sheetsToCopy = VBA.Array("RWF CPC")
' 'VBA.' ensures a zero-based array no matter what ('Option Base'-related).
' If you don't do this, instead of both occurrences of '0',
' use the recommended (more accurate) 'LBound(sheetsToCopy)'.
' Declare new variables to be used in the loop.
Dim NewWorkbook As Workbook, OldWorksheet As Worksheet, i As Long
' Loop through the worksheet names in the array.
For i = 0 To UBound(sheetsToCopy)
' Reference the worksheet to be copied.
Set OldWorksheet = ThisWorkbook.Sheets(sheetsToCopy(i))
If i = 0 Then ' on the first iteration...
' Add a new workbook containing only the first copied worksheet.
OldWorksheet.Copy
' Reference this new workbook.
Set NewWorkbook = Workbooks(Workbooks.Count)
Else ' on any but the first iteration
' Copy the worksheet as the last sheet in the new workbook.
OldWorksheet.Copy After:=NewWorkbook.Sheets(NewWorkbook.Sheets.Count)
End If
Next i
' Break links in the new workbook.
NewWorkbook.BreakLink Name:=ThisWorkbook.Name, Type:=xlExcelLinks
' Retrieve the base name of the new workbook.
Dim saveName As String
saveName = ThisWorkbook.Sheets("Macros").Range("B13").Value
' Save the new workbook in the original folder.
Application.DisplayAlerts = False ' overwrite without confirmation.
NewWorkbook.SaveAs ThisWorkbook.Path & "\" & saveName
Application.DisplayAlerts = True
' Inform.
MsgBox "CPC saved.", vbInformation
ProcExit:
Exit Sub
ClearError:
' Continue error-handling routine.
MsgBox "Run-time error '" & Err.Number & "':" & vbLf & vbLf & Err.Description
Resume ProcExit
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
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
I have the following macro
(Macro than rename the sheet with the value of cell B4 and then create one workbook for each sheet.)
Sub RenameTabs()
'UpdatebyTony
For x = 1 To Sheets.Count
If Worksheets(x).Range("B4").Value <> "" Then
Sheets(x).Name = Worksheets(x).Range("B4").Value
End If
Next
Dim xPath As String
xPath = Application.ActiveWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In ThisWorkbook.Sheets
xWs.Copy
Application.ActiveWorkbook.SaveAs Filename:=xPath & "\" & xWs.Name & ".xls"
Application.ActiveWorkbook.Close False
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
But this means I have to go and copy the macro in each excel file and run it.
I would like to be able to run de macro and it open a dialog where it ask me to choose the excel file that I want to rename the sheets and separate? Is that possible?
I know very little about VBA
Get the path of the workbook you like to perform the macro from FileDialog. You can use
Application.FileDialog
https://msdn.microsoft.com/en-us/library/office/ff836226.aspx
Open the workbook and set a reference for it.
set wb =Application.Workbooks.Open(filepath)
On your current sub RenameTabs, replace Application.ActiveWorkbook, ThisWorkBook with wb. Also, you need to properly reference the Sheets, Worksheets, ... to wb. Alternatively, you should make it sure that wb is the ActiveWorkbook (wb.Activate) (you can break the code if you switch to another excel file when it is still processing)
I am having this weird problem when saving my sheet into onedrive sync folder. Basically what i am doing with the below code is that I copy a sheet from my workbook then save it into a sync folder. When it does this, a saved copy with the filename that is stored in a specific cell together with another copy with the same saved name with a 1 at the back of the file name will appear in the sync folder. When i step over to test the code, no such error occur. The error only occur if I run the macro. May i know why? Below is my code;
Sub SheetSplit1()
'
'Creates an individual workbook for each worksheet in the active workbook.
'
Dim wbDest As Workbook
Dim wbSource As Workbook
Dim sht As Object
Dim strSavePath As String
Dim sname As String
Dim relativepath As String
Set wbSource = ActiveWorkbook
'For Each sht In wbSource.Sheets
Sheet10.Copy
Set wbDest = ActiveWorkbook
sname = Sheet9.Range("I5") & "_" & _
Format(Sheet9.Range("I8"), "ddmmmyyyy") & ".xlsx"
relativepath = "C:\Users\" & Environ$("Username") & _
"\SharePoint\Open Project Transition Check - Doc\Transition Dashboard Report\" & sname 'use path of wbSource
'wbDest.Sheets(1).Range("A1").Clear 'clear filename from new workbook cell A1
Application.DisplayAlerts = False
ActiveWorkbook.CheckCompatibility = False
ActiveWorkbook.SaveAs Filename:=relativepath, FileFormat:=xlOpenXMLWorkbook, _
CreateBackup:=False
Application.DisplayAlerts = True
wbDest.Close False 'close the newly saved workbook without saving (we already saved)
'Next
MsgBox "DashBoard Report Saved!"
End Sub
Greatly appreciate anyone who could assist me. Thanks.
I wish I could give a definitive answer, or Microsoft would contribute.
I have similar connected problems. It seems that another version of the file may be or "appear to be" open elsewhere, thus preventing excel/Onedrive from completing the save action.
Rather than overwrite it(lets face t, that was the command) it creates a "version" filename(1).
I am guessing this is the same as when you do it manually and you are asked to resolve a conflict.
So far I have failed to find out how you can discover and solve the problem in code.
I solved it in one instance by mapping a drive on the offending desktop and first closing any open versions before save, but that is not a robust long term solution.
Test this by setting Application.DisplayAlerts = True and capturing errors.
"On error got catch" after the last dimension line then
"exit function
catch:
msgbox err.description"
before "end sub"