Forum Discussion
SOLVED - "Method 'SaveAs' of object '_Workbook' failed" (1004) when saving into same file location
- Mar 20, 2022
Update:
So, the variable "PathAndFile_Name" is the defined path and name/type in the SaveAs dialog. For example, is "C:\Users\MY NAME\Desktop\CUSTOM NAME.xlsx"
And, the variable "File_Name" is just the defined name/type in the SaveAs dialog. For example, "CUSTOM NAME.xlsx"
Based on most of the internet's examples, I thought the "FileName:=" was to include the full path. But, while still getting the runtime error 1004 and reading https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.saveas more carefully, I tried using just "File_Name" instead of "PathAndFile_Name" in "ActiveWorkbook.SaveAs" (line 48 below).
I don't know how or why but I solved it by changing "PathAndFile_Name" to just "File_Name", and it will no longer produce an error when saving in the same file location as the main ".xlsm" workbook and still works with other user-selected file locations.
What's weird is using the full path in "ActiveWorkbook.SaveAs FileName:=" works in every way but the same file location as the main .xlsm. But, just using the name works in any location. If someone understands why I'd love to know, but regardless am glad it works.
For anyone looking for a complete SaveAs code (using "Application.FileDialog(msoFileDialogSaveAs)"), feel free to paste this working example into your project then edit as needed:
Sub SaveAs_YourFile() 'Set then launch SaveAs dialog (YOU CAN EDIT THIS AS NEEDED): On Error GoTo SaveAs_Error_Handler Application.ScreenUpdating = False Dim ObFD As FileDialog Dim File_Name As String Dim PathAndFile_Name As String File_Name = "YOUR DEFAULT NAME" 'Set default (suggested) File Name Set ObFD = Application.FileDialog(msoFileDialogSaveAs) With ObFD .Title = "Save As - YOUR PROJECT NAME" .ButtonName = "S&ave" .InitialFileName = ThisWorkbook.Path & "\" & File_Name 'Default file location and File Name .FilterIndex = 1 'File Type (.xlsx) .AllowMultiSelect = False .InitialView = msoFileDialogViewDetails .Show If .SelectedItems.count = 0 Then MsgBox "Save As canceled", vbExclamation, "Save As - YOUR PROJECT NAME" Application.ScreenUpdating = True: Exit Sub Else PathAndFile_Name = .SelectedItems(1) End If End With 'Verify file type (YOU CAN EDIT/REMOVE THIS AS NEEDED): If Right(PathAndFile_Name, Len(PathAndFile_Name) - InStrRev(PathAndFile_Name, ".") + 1) <> ".xlsx" Then MsgBox "Note: You can only save as an ""Excel Workbook (*.xlsx)"" file type. The file type will be changed from """ _ & Right(PathAndFile_Name, Len(PathAndFile_Name) - InStrRev(PathAndFile_Name, ".") + 1) & """ to " & """.xlsx""." _ , vbExclamation, "Save As - YOUR PROJECT NAME" PathAndFile_Name = Replace(PathAndFile_Name, Right(PathAndFile_Name, Len(PathAndFile_Name) - _ InStrRev(PathAndFile_Name, ".") + 1), ".xlsx"): End If 'Check if file type is not .xlsx If Right(PathAndFile_Name, Len(PathAndFile_Name) - InStrRev(PathAndFile_Name, "\")) = ".xlsx" Then PathAndFile_Name = Left(PathAndFile_Name, InStrRev(PathAndFile_Name, Application.PathSeparator)) _ & Replace(File_Name, ".xlsm", ".xlsx"): End If 'Check if file name is literally just .xlsx 'Copy YOUR SHEET into new workbook then edit (YOU CAN EDIT THIS AS NEEDED): Application.DisplayAlerts = False File_Name = Right(PathAndFile_Name, Len(PathAndFile_Name) - InStrRev(PathAndFile_Name, "\")) 'Update File Name to user's input ThisWorkbook.Sheets("" & Sheet1.Name & "").Copy 'SPECIFY THIS AS NEEDED 'Note: The Sheets.copy is what creates a new workbook, thus the following code to save it then work _ with it. With this method, only one sheet copy occurs at a time with the applicable year loaded _ beforehand. "If you don't specify either Before or After, Microsoft Excel creates a new workbook _ that contains the copied Worksheet object." (https://docs.microsoft.com/en-us/office/vba/api/excel.worksheet.copy) ActiveWorkbook.SaveAs fileName:=File_Name, FileFormat:=xlOpenXMLWorkbook 'New workbook save and activate With Excel.Workbooks(File_Name).Sheets '<YOUR CODE TO EDIT THE NEW WORKBOOK SHEET HERE> End With Excel.Workbooks(File_Name).Activate Excel.Workbooks(File_Name).Close SaveChanges:=True 'New workbook save and close Application.DisplayAlerts = True 'Note: For full name of new workbook: "ObFD.InitialFile_Name" 'For more information about Excel file types: https://docs.microsoft.com/en-us/office/vba/api/excel.xlfileformat 'Original Code: https://stackoverflow.com/questions/60696187/save-a-new-excel-file-to-a-user-given-path-with-filedialog-msofiledialogsaveas 'Error handler (YOU CAN EDIT THIS AS NEEDED): If 1 = 2 Then SaveAs_Error_Handler: Application.ScreenUpdating = True: Application.DisplayAlerts = True MsgBox "An unexpected error occurred while saving " & File_Name & "!", vbCritical, "Save As - YOUR PROJECT NAME" Else Application.ScreenUpdating = True MsgBox File_Name & " saved successfully.", vbInformation, "Save As - YOUR PROJECT NAME" End If End Sub
As far as I could understand, your file is equipped with a macro, so it cannot be saved in xlsx without an error message. You have to do this in xlsm to use the macro
or if you really want to save it in xlsx, turn off / save / turn on the error message.
here is a simple pattern
Sub SaveAsXlsx()
'Save the file without macros (as an .xlsx file).
Application.DisplayAlerts = False 'Error alerts off
'here with direct path specification
ActiveWorkbook.SaveAs Filename:=Environ("USERPROFILE") & "\Desktop\Testfile.xlsx", _
FileFormat:=xlOpenXMLWorkbook
Application.DisplayAlerts = True ' Displays error messages
end sub
I hope that this approach leads to the cancellation of the message, I haven't tried it.
At the same time, if this does not help you, it would be an advantage to know about the Excel version, operating system and storage medium.
I know I don't know anything (Socrates)
- KendetharMar 12, 2022Iron ContributorNikolinoDE,
P.s. ThisWorkbook.Sheets("Troop to Task - Tracker").Copy (line 58) is what creates a new workbook.
Explained better: https://docs.microsoft.com/en-us/office/vba/api/excel.worksheet.copy- NikolinoDEMar 13, 2022Gold Contributor
I don't really know how I can help you either. If none of the specialists here come up with a solution suggestion, take a look here as well, maybe this "All Questions" will help you further.
Thank you for your patience and time.
I know I don't know anything (Socrates)
- KendetharMar 20, 2022Iron Contributor
Update:
So, the variable "PathAndFile_Name" is the defined path and name/type in the SaveAs dialog. For example, is "C:\Users\MY NAME\Desktop\CUSTOM NAME.xlsx"
And, the variable "File_Name" is just the defined name/type in the SaveAs dialog. For example, "CUSTOM NAME.xlsx"
Based on most of the internet's examples, I thought the "FileName:=" was to include the full path. But, while still getting the runtime error 1004 and reading https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.saveas more carefully, I tried using just "File_Name" instead of "PathAndFile_Name" in "ActiveWorkbook.SaveAs" (line 48 below).
I don't know how or why but I solved it by changing "PathAndFile_Name" to just "File_Name", and it will no longer produce an error when saving in the same file location as the main ".xlsm" workbook and still works with other user-selected file locations.
What's weird is using the full path in "ActiveWorkbook.SaveAs FileName:=" works in every way but the same file location as the main .xlsm. But, just using the name works in any location. If someone understands why I'd love to know, but regardless am glad it works.
For anyone looking for a complete SaveAs code (using "Application.FileDialog(msoFileDialogSaveAs)"), feel free to paste this working example into your project then edit as needed:
Sub SaveAs_YourFile() 'Set then launch SaveAs dialog (YOU CAN EDIT THIS AS NEEDED): On Error GoTo SaveAs_Error_Handler Application.ScreenUpdating = False Dim ObFD As FileDialog Dim File_Name As String Dim PathAndFile_Name As String File_Name = "YOUR DEFAULT NAME" 'Set default (suggested) File Name Set ObFD = Application.FileDialog(msoFileDialogSaveAs) With ObFD .Title = "Save As - YOUR PROJECT NAME" .ButtonName = "S&ave" .InitialFileName = ThisWorkbook.Path & "\" & File_Name 'Default file location and File Name .FilterIndex = 1 'File Type (.xlsx) .AllowMultiSelect = False .InitialView = msoFileDialogViewDetails .Show If .SelectedItems.count = 0 Then MsgBox "Save As canceled", vbExclamation, "Save As - YOUR PROJECT NAME" Application.ScreenUpdating = True: Exit Sub Else PathAndFile_Name = .SelectedItems(1) End If End With 'Verify file type (YOU CAN EDIT/REMOVE THIS AS NEEDED): If Right(PathAndFile_Name, Len(PathAndFile_Name) - InStrRev(PathAndFile_Name, ".") + 1) <> ".xlsx" Then MsgBox "Note: You can only save as an ""Excel Workbook (*.xlsx)"" file type. The file type will be changed from """ _ & Right(PathAndFile_Name, Len(PathAndFile_Name) - InStrRev(PathAndFile_Name, ".") + 1) & """ to " & """.xlsx""." _ , vbExclamation, "Save As - YOUR PROJECT NAME" PathAndFile_Name = Replace(PathAndFile_Name, Right(PathAndFile_Name, Len(PathAndFile_Name) - _ InStrRev(PathAndFile_Name, ".") + 1), ".xlsx"): End If 'Check if file type is not .xlsx If Right(PathAndFile_Name, Len(PathAndFile_Name) - InStrRev(PathAndFile_Name, "\")) = ".xlsx" Then PathAndFile_Name = Left(PathAndFile_Name, InStrRev(PathAndFile_Name, Application.PathSeparator)) _ & Replace(File_Name, ".xlsm", ".xlsx"): End If 'Check if file name is literally just .xlsx 'Copy YOUR SHEET into new workbook then edit (YOU CAN EDIT THIS AS NEEDED): Application.DisplayAlerts = False File_Name = Right(PathAndFile_Name, Len(PathAndFile_Name) - InStrRev(PathAndFile_Name, "\")) 'Update File Name to user's input ThisWorkbook.Sheets("" & Sheet1.Name & "").Copy 'SPECIFY THIS AS NEEDED 'Note: The Sheets.copy is what creates a new workbook, thus the following code to save it then work _ with it. With this method, only one sheet copy occurs at a time with the applicable year loaded _ beforehand. "If you don't specify either Before or After, Microsoft Excel creates a new workbook _ that contains the copied Worksheet object." (https://docs.microsoft.com/en-us/office/vba/api/excel.worksheet.copy) ActiveWorkbook.SaveAs fileName:=File_Name, FileFormat:=xlOpenXMLWorkbook 'New workbook save and activate With Excel.Workbooks(File_Name).Sheets '<YOUR CODE TO EDIT THE NEW WORKBOOK SHEET HERE> End With Excel.Workbooks(File_Name).Activate Excel.Workbooks(File_Name).Close SaveChanges:=True 'New workbook save and close Application.DisplayAlerts = True 'Note: For full name of new workbook: "ObFD.InitialFile_Name" 'For more information about Excel file types: https://docs.microsoft.com/en-us/office/vba/api/excel.xlfileformat 'Original Code: https://stackoverflow.com/questions/60696187/save-a-new-excel-file-to-a-user-given-path-with-filedialog-msofiledialogsaveas 'Error handler (YOU CAN EDIT THIS AS NEEDED): If 1 = 2 Then SaveAs_Error_Handler: Application.ScreenUpdating = True: Application.DisplayAlerts = True MsgBox "An unexpected error occurred while saving " & File_Name & "!", vbCritical, "Save As - YOUR PROJECT NAME" Else Application.ScreenUpdating = True MsgBox File_Name & " saved successfully.", vbInformation, "Save As - YOUR PROJECT NAME" End If End Sub
- KendetharMar 12, 2022Iron ContributorNikolinoDE,
I did use Application.DisplayAlerts = False (line 47) but won't prevent the runtime error (VBA cannot execute). And, the goal is to save the new file as a .xlsx, which it does fine in every other scenario, except when the file path is the same as the master file (.xlsm). I cannot wrap my head around it.
And to respond to your specific response, I'm not saving the file the macro is ran on but rather creating a brand new .xlsx then saving that. The code is all ran from a .xlsm, which itself is not saved or changed.