Yes, you can save and overwrite an Excel workbook using VBA with the ThisWorkbook.Save method. This saves the current workbook to its existing file path, overwriting the previous version. If the workbook has never been saved, you'll need to use SaveAs to specify a path first. This guide covers both methods, along with error handling and tips for automating your saves.
What You'll Need
- Microsoft Excel (2010 or later is fine; the steps work in all modern versions).
- A workbook you want to save with VBA. It can be a macro-enabled workbook (.xlsm) or a standard one (.xlsx) if you're just testing.
- Access to the Visual Basic for Applications (VBA) editor. Press Alt + F11 to open it.
- Basic familiarity with inserting a module and running a macro. If you're new, follow the steps below carefully.
Step-by-Step
1. Open the VBA Editor
In Excel, press Alt + F11 to open the VBA editor. Alternatively, go to the Developer tab and click Visual Basic. If you don't see the Developer tab, you may need to enable it in Excel's options (File > Options > Customize Ribbon > check Developer).
2. Insert a Module
In the VBA editor, go to Insert > Module. This creates a new code module where you can write your macro. Modules are where you store general-purpose code that isn't attached to a specific worksheet or workbook event.
3. Write a Simple Save Macro
In the module window, type the following code:
Sub SaveWorkbook()
ThisWorkbook.Save
End Sub
This macro saves the workbook that contains the code. If the file has been saved before, it overwrites the existing file with the current content. If it's a new unsaved workbook, Excel will prompt you to choose a location and file name (this is the same as using Save As).
4. Run the Macro
To run the macro, press F5 while the cursor is inside the macro, or go to Run > Run Sub/UserForm. You can also close the VBA editor and use Alt + F8 in Excel to open the Macro dialog, select SaveWorkbook, and click Run.
5. Save to a Specific Path with SaveAs
If you need to save to a specific folder or with a specific file name (including overwriting a different file), use the SaveAs method. Here's an example that saves to a fixed path:
Sub SaveToSpecificPath()
Dim filePath As String
filePath = "C:\MyFolder\MyWorkbook.xlsm"
ThisWorkbook.SaveAs Filename:=filePath, FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub
Note that FileFormat is optional. If you omit it, Excel saves in the default format for the file type. For a macro-enabled workbook, use xlOpenXMLWorkbookMacroEnabled (value 52). For a standard workbook, use xlOpenXMLWorkbook (value 51). If the file already exists, SaveAs will overwrite it without prompting (unless you set DisplayAlerts to False, which we'll cover later).
6. Overwrite Without Prompting
By default, when you use SaveAs on an existing file, Excel may ask for confirmation. To suppress that prompt and automatically overwrite, set Application.DisplayAlerts to False before saving, then set it back to True:
Sub OverwriteWithoutPrompt()
Application.DisplayAlerts = False
ThisWorkbook.SaveAs Filename:="C:\MyFolder\MyWorkbook.xlsx", FileFormat:=51
Application.DisplayAlerts = True
End Sub
This is useful when you're automating a process and don't want the macro to stop for user input. Remember to always reset DisplayAlerts to True after the save, or you might suppress other important alerts later in your code.
7. Save a Copy While Keeping the Original
If you want to overwrite the original file but also keep a backup, you can first copy the file to a backup location, then save. For example:
Sub SaveWithBackup()
Dim backupPath As String
backupPath = "C:\Backup\MyWorkbook_Backup.xlsx"
ThisWorkbook.SaveCopyAs backupPath
ThisWorkbook.Save
End Sub
SaveCopyAs saves a copy to the specified path without changing the current file. Then Save overwrites the original. This is a safe way to keep a history of changes.
8. Save All Open Workbooks
If you have multiple workbooks open and want to save them all, loop through the Workbooks collection:
Sub SaveAllWorkbooks()
Dim wb As Workbook
For Each wb In Workbooks
If wb.Path <> "" Then
wb.Save
Else
' Unsaved workbook - skip or handle separately
MsgBox "Workbook " & wb.Name & " has never been saved. Skipping."
End If
Next wb
End Sub
This checks if each workbook has a Path (meaning it has been saved before). If not, it skips it to avoid prompting for a file name.
9. Trigger Save on Workbook Close
To automatically save and overwrite when the workbook closes, you can use the BeforeClose event. In the VBA editor, double-click ThisWorkbook in the Project Explorer and enter:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
ThisWorkbook.Save
End Sub
This will save the workbook every time you close it, without asking. Be careful: if you don't want to save every time, you might want to add a confirmation dialog instead.
Common Mistakes
- Forgetting to reset DisplayAlerts: If you set
Application.DisplayAlerts = Falseand don't set it back toTrue, Excel may not show important warnings later, like when closing with unsaved changes. Always reset it. - Using SaveAs on an unsaved workbook without a path: If you try to use
Saveon a new workbook, it will prompt for a file name. UseSaveAswith a full path to avoid that. - Hard-coding file paths that don't exist: If the folder in your
SaveAspath doesn't exist, you'll get an error. Make sure the folder exists, or useMkDirto create it first. - Not specifying the file format: If you use
SaveAswithout aFileFormat, Excel may use the default format, which could be different from what you expect (e.g., saving a macro-enabled workbook as .xlsx and losing the macros). - Overwriting without a backup: If your code has a bug, you might overwrite a good file with a broken one. Use
SaveCopyAsor make a manual backup before running new code.
Tips
- Use
ThisWorkbookto refer to the workbook containing the code. This avoids confusion if you have multiple workbooks open. - If you want to save the active workbook (the one the user is currently looking at), use
ActiveWorkbook.Saveinstead. But be aware thatActiveWorkbookcan change if the user clicks another window during the macro. - For a timestamped backup, you can create a dynamic file name like
"MyWorkbook_" & Format(Now, "yyyymmdd_hhmmss") & ".xlsx". This helps you keep multiple versions without overwriting. - Test your macro on a copy of your workbook first to ensure it doesn't corrupt anything.
- If you're saving to a network drive, be aware that network interruptions can cause errors. Consider adding error handling to retry or notify the user.
Troubleshooting
Error: "Method 'SaveAs' of object '_Workbook' failed"
This usually means the file path is invalid (folder doesn't exist) or the file is open in another program. Check that the folder exists and the file isn't open elsewhere.
Error: "Compile error: Sub or Function not defined"
This means you mistyped a method name or used a variable that isn't declared. Check the spelling and ensure you have Option Explicit at the top of the module to catch typos.
Macro runs but doesn't save anything
If you're using ThisWorkbook.Save and the workbook has never been saved, it will prompt for a location. If you're not seeing the prompt, check if DisplayAlerts is set to False somewhere else in your code. Also, make sure the macro is actually running (add a MsgBox to confirm).
File gets saved as .xlsx instead of .xlsm and macros are lost
This happens when you use SaveAs without specifying FileFormat. Always specify the format: xlOpenXMLWorkbookMacroEnabled for .xlsm, xlOpenXMLWorkbook for .xlsx, or xlExcel8 for .xls compatibility.
Excel crashes or freezes when saving
This can be due to large files, complex formatting, or add-ins. Try saving manually first. If that works, the issue might be in your code (e.g., an infinite loop). Use Application.StatusBar to track progress and add DoEvents to allow the system to respond.
Frequently Asked Questions
Can I overwrite a file that is currently open in another Excel instance?
No. If a file is open in another Excel process, you'll get a permission error. You need to close the other instance or save to a different name.
How do I save to a relative path (e.g., same folder as the workbook)?
Use ThisWorkbook.Path to get the current folder. For example: ThisWorkbook.SaveAs ThisWorkbook.Path & "\NewName.xlsx". If the workbook is unsaved, Path is empty, so you'll need to handle that.
Is there a way to save without closing the workbook?
Yes, Save and SaveAs both save the file without closing it. The workbook remains open.
What's the difference between Save and SaveAs?
Save saves to the existing file path and name. SaveAs lets you specify a new path, name, or file format. If the file has never been saved, Save behaves like SaveAs and prompts for a location.
Can I undo a save in VBA?
No. Once saved, the previous version is overwritten. You cannot undo from VBA. That's why it's wise to keep backups before running code that overwrites.
How do I save a workbook as a PDF using VBA?
Use ExportAsFixedFormat. Example: ThisWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:="C:\MyFolder\MyWorkbook.pdf". This creates a PDF but does not overwrite the Excel file.