You finish a monthly report, save it, and move on. The next morning, a colleague needs the figures as they appeared before a late-evening edit. Or perhaps a formula was replaced by a value, a worksheet disappeared, or a shared folder now contains several files named Final_v2_revised_USE_THIS.xlsx.
Excel’s Undo command is helpful, but it is not a version-history system. It may disappear after closing the workbook, and it cannot recover a clean copy from last Tuesday.
A small VBA routine can create a backup every time a workbook is saved, give each copy an understandable timestamp, and remove old copies according to a clear retention rule. This is especially useful for workbooks that act as operational tools rather than one-off calculations.
The goal is not to replace an organisation’s backup platform. It is to build a practical safety net: a local, visible record of prior workbook states that you can restore when an ordinary save becomes an expensive mistake.
🧭 What this VBA system is designed to do
An automatic backup system copies the current workbook to a separate folder during the save process. Each copy receives a unique name, usually containing the workbook name and the date and time.
Version history means those copies are retained rather than overwritten. For example, saving Budget.xlsx at 09:15 and 14:30 could create two recoverable snapshots. A cleanup step can later remove versions older than a chosen number of days.
This approach works best for macro-enabled workbooks because the VBA code must travel with the file. Save the main workbook as .xlsm.
🛟 Why ordinary Save is not enough
Save replaces the previous state of the same file. That is normally desirable, but it means a bad change can replace the good version with no separate recovery point.
Cloud storage services may provide their own version history, and that can be excellent protection. Availability and retention, however, depend on the service, account settings, permissions, and whether the workbook is stored in a synchronized location. A VBA archive is a separate layer, not a competitor to those tools.
Think of the workbook as a draft contract. Saving updates the current draft; versioned backup places dated photocopies in a filing cabinet.
🎯 Decide what counts as a version
Before writing code, decide when a backup is worth creating. A copy on every save gives the most detailed history, but repeated Ctrl+S presses can create many nearly identical files.
For most personal or departmental workbooks, backup-on-save is simple and predictable. For very large workbooks or frequently saved models, you might instead back up only after a meaningful change, once per day, or when a user clicks a dedicated button.
Start with the straightforward rule: create one version before each normal save. You can refine it after observing how many files it produces.
📁 Choose a backup location deliberately
Keep backups outside the workbook’s working folder when possible. Otherwise, a user may open an old copy by accident, edit it, and confuse it with the live file.
A sensible structure is a folder named Backups beside the original file, then a subfolder named after the workbook. This keeps related versions together while making the active file easy to identify.
You may use a network drive or synchronized cloud folder, but test it first. A disconnected drive, slow synchronization, or restricted permission can cause the backup step to fail during a save.
🧱 Understand the two VBA locations you need
This project uses two places in the Visual Basic Editor. Event code belongs in the ThisWorkbook object because it responds to actions involving that specific workbook. Reusable procedures belong in a standard module.
Open the editor with Alt+F11. In the Project Explorer, double-click ThisWorkbook. Then choose Insert > Module to create a standard module, often called Module1.
Keeping these roles separate makes the project easier to read: ThisWorkbook says when to run; the module says how to create and maintain backups.
🔐 Save the workbook as a macro-enabled file
Choose File > Save As and select Excel Macro-Enabled Workbook (*.xlsm). An .xlsx file cannot retain VBA code.
This does not make every copy unsafe or unshareable. It simply means recipients must decide whether to enable macros when opening the macro-enabled workbook. Your backup copies will also remain macro-enabled if the source workbook is.
Never rely on macros as a security boundary. VBA can be disabled, modified by users who have access, or blocked by an organisation’s macro policies.
⚙️ Use the BeforeSave workbook event
The Workbook_BeforeSave event runs immediately before Excel saves the workbook. It is an appropriate trigger because the routine can archive the version that existed just before the new save replaces it.
Place the following event procedure in ThisWorkbook:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, _
Cancel As Boolean)
CreateVersionBackup
End Sub
The SaveAsUI and Cancel arguments are supplied by Excel. The procedure above does not change either one; it simply calls the backup routine.
🔄 Prevent the backup from triggering itself
Saving a copy may itself activate workbook events. If that happens unchecked, the backup code can call itself repeatedly or leave Excel’s events disabled after an error.
The standard safeguard is Application.EnableEvents = False before the copy operation and restoring it to True in a cleanup block. Restoring application settings is not optional; it protects Excel after unexpected errors.
A second safeguard is to skip the routine when the workbook has never been saved. Until it has a folder, ThisWorkbook.Path is an empty string.
🧩 Build the core backup procedure
Put this procedure in a standard module. It creates the folder if needed, constructs a timestamped filename, and uses SaveCopyAs to write the copy.
Public Sub CreateVersionBackup()
Dim backupFolder As String
Dim backupFile As String
Dim baseName As String
On Error GoTo SafeExit
If ThisWorkbook.Path = "" Then Exit Sub
If LCase$(ThisWorkbook.Path) Like "*\\backups*" Then Exit Sub
Application.EnableEvents = False
backupFolder = ThisWorkbook.Path & "\Backups\" & _
CleanFileName(ThisWorkbook.Name)
If Dir(backupFolder, vbDirectory) = "" Then
MkDir ThisWorkbook.Path & "\Backups"
MkDir backupFolder
End If
baseName = FileNameWithoutExtension(ThisWorkbook.Name)
backupFile = backupFolder & "\" & baseName & "_" & _
Format(Now, "yyyy-mm-dd_hh-nn-ss") & ".xlsm"
ThisWorkbook.SaveCopyAs backupFile
DeleteOldBackups backupFolder, 30
SafeExit:
Application.EnableEvents = True
End Sub
This example assumes a Windows-style path and an .xlsm source file. Later sections explain the helper procedures and the adjustment needed for other extensions.
🕒 Make timestamps sort correctly
The format yyyy-mm-dd_hh-nn-ss is deliberately ordered from largest time unit to smallest. Alphabetical filename order then matches chronological order.
In VBA date formats, nn means minutes. Using mm in that position can produce a month instead of minutes, a small detail that can create duplicate names or misleading timestamps.
Colons are not allowed in Windows filenames, so use hyphens between time values. The resulting name is readable: Budget_2025-03-08_14-30-12.xlsm.
🏷️ Preserve the original file extension
Hard-coding .xlsm is fine when the project is strictly for macro-enabled workbooks. If you adapt the module for other formats, preserve the source file extension instead.
The following helper obtains the name without its final extension:
Public Function FileNameWithoutExtension(ByVal fileName As String) As String
FileNameWithoutExtension = Left$(fileName, _
InStrRev(fileName, ".") - 1)
End Function
You can obtain the extension with Mid$(ThisWorkbook.Name, InStrRev(ThisWorkbook.Name, ".")). Be cautious with unusual names that do not contain a period; a production-ready routine should validate that case.
🧹 Clean names used for folders
A workbook name can contain characters that Windows does not allow in folder names, such as a colon or question mark. A helper function prevents the backup folder creation from failing for that reason.
Public Function CleanFileName(ByVal text As String) As String
Dim badCharacters As Variant
Dim item As Variant
badCharacters = Array("\", "/", ":", "*", "?", """, "<", ">", "|")
For Each item In badCharacters
text = Replace(text, item, "_")
Next item
CleanFileName = text
End Function
This function is used only for the folder name. The version file itself is built from the base filename and a controlled timestamp, which keeps naming predictable.
📦 Know what SaveCopyAs actually saves
SaveCopyAs creates a copy without changing the open workbook’s name, path, or current editing session. That is why it is preferable to using Save As for automated archive copies.
One subtle point matters: the copy reflects the workbook’s state in memory at the time of the call. In a BeforeSave event, it can include edits that have not yet been written to the primary file, which is usually exactly what you want from a pre-save snapshot.
It does not copy every external dependency. Linked workbooks, external data connections, linked images, and files referenced by formulas remain separate resources.
🗂️ Create folders safely
MkDir can create only one level at a time. That is why the core example creates Backups before creating the workbook-specific folder.
The simple folder test works for a local structure under an existing workbook folder. If your desired destination has several missing parent folders, build and validate each level rather than assuming one MkDir call will build the whole path.
Also consider folder permissions. A workbook opened from a read-only location or protected network share may be editable in Excel while still being unable to create a sibling folder.
🧽 Add a retention policy
Version history is useful only while it remains manageable. A retention policy defines how long old backups stay. The example uses 30 days, but the right period depends on the workbook’s purpose and how quickly mistakes tend to be discovered.
Add this procedure to the same standard module:
Public Sub DeleteOldBackups(ByVal backupFolder As String, _
ByVal daysToKeep As Long)
Dim fileName As String
Dim fullPath As String
fileName = Dir(backupFolder & "\*.xls*")
Do While fileName <> ""
fullPath = backupFolder & "\" & fileName
If FileDateTime(fullPath) < DateAdd("d", -daysToKeep, Now) Then
Kill fullPath
End If
fileName = Dir()
Loop
End Sub
Deletion is permanent from the perspective of this routine. Test with a temporary folder before trusting it with records that must be retained.
⚖️ Choose retention based on the work
Thirty calendar days is merely an example, not a universal policy. A personal planning workbook may need only a short history. A financial close workbook may need a longer, formally managed archive outside VBA.
| Workbook situation | Useful starting approach | Main consideration |
|---|---|---|
| Personal analysis | Keep recent daily backups | Convenience and disk space |
| Frequently edited team tool | Keep more versions, review monthly | Shared access and duplicate work |
| Controlled business record | Use approved storage and formal retention | Audit, access, and legal requirements |
Do not let a VBA cleanup rule override organisational retention requirements. Where records management matters, ask the responsible team what belongs in an approved archive.
🚫 Avoid deleting the wrong files
The cleanup procedure targets files matching *.xls* in the backup folder. That is convenient, but it assumes the folder contains only versions created by this system.
Do not point cleanup at a broad shared folder. Better still, use a dedicated folder for each workbook, as the core routine does. Narrow scope is one of the most reliable safeguards in file automation.
During testing, comment out the Kill fullPath line and use Debug.Print fullPath to inspect what would be deleted in the Immediate Window.
🧪 Test with a disposable workbook first
Copy the workbook or build a small test file before enabling automatic deletion. Save it several times and inspect the generated folder, filenames, timestamps, and file contents.
Test the situations that are likely in real use:
- Saving after edits to values, formulas, and worksheets.
- Saving twice within a short interval.
- Saving from a folder with no existing Backups folder.
- Opening the workbook when macros are disabled.
- Working from a location with restricted write permission.
Test recovery too. A backup strategy is not proven because copies exist; it is proven when you can locate, open, and restore a suitable copy without guesswork.
🔍 Verify the backup without opening it
At first, inspect the backup folder after every test save. Confirm that the file size is plausible and that its timestamp corresponds to the save activity.
You can add a simple status message during development:
Application.StatusBar = "Backup created: " & backupFile
Remember to clear it later with Application.StatusBar = False. Message boxes are generally a poor choice for automatic events because they interrupt ordinary saving.
🧯 Handle errors without hiding them
The core routine uses On Error GoTo SafeExit so events are restored even if folder creation or copying fails. This is safer than allowing Excel to remain in a state where events no longer run.
But silently swallowing every error can conceal a broken backup system. During development, add logging or a carefully chosen notification. For example, write the error number and description to a hidden log sheet, provided the logging itself does not cause another save loop.
A balanced design restores Excel settings first, then reports failures in a way suitable for the workbook’s users.
🧾 Keep a lightweight backup log
A log sheet can record the backup path, date, username, and outcome. This helps users answer a practical question: “Was a version actually created before I saved?”
For a simple implementation, create a worksheet named Backup Log and append a row after SaveCopyAs. If the workbook is shared or performance-sensitive, a text log in the backup folder may be less intrusive.
Do not treat an editable worksheet log as audit-proof evidence. It is useful operational information, not a tamper-resistant audit trail.
👥 Consider shared and co-authored workbooks
Traditional VBA event automation can be awkward in modern co-authoring workflows. Different people may save changes at overlapping times, and a locally running macro only sees the session in which it executes.
Separate backup folders by user or device if simultaneous edits make filenames or ownership unclear. For example, append Environ$("Username") after cleaning it for a filename.
For highly collaborative workbooks, built-in version history in the approved shared platform is often the primary recovery tool. VBA versions can still help, but they should not create false confidence about a single, complete change timeline.
☁️ Be careful with OneDrive, SharePoint, and network paths
A synchronized folder may report a local path while the cloud service uploads later. A successfully created local backup does not necessarily mean it has already reached the cloud.
Network folders introduce another issue: a connection can fail midway through work. Your error handling should let the normal workbook save proceed or stop it according to the business need; that is a design decision, not a purely technical one.
If a backup is mandatory before saving, set Cancel = True in the event procedure when the backup fails. This is stricter, but it can frustrate users during a temporary network outage.
💾 Account for large workbooks and slow saves
Every version is a full workbook copy. Large models with images, Power Query data, PivotTables, or many worksheets can make backup-on-save noticeably slower and consume substantial storage.
Possible responses include backing up less often, retaining fewer copies, archiving only at milestones, or storing the workbook in a system with native version history. Do not remove protection blindly; match the method to the cost of each copy.
Measure the experience with a representative workbook. A routine that feels instant on a tiny test file may be disruptive in a large operational model.
🧮 Decide whether recalculation belongs in the process
Excel may be configured for automatic or manual calculation. The backup routine copies the workbook as it currently exists; it does not guarantee that every formula has been recalculated immediately beforehand.
Calling ThisWorkbook.Worksheets.Calculate or Application.Calculate may be appropriate for a reporting workbook, but it can add time and alter the moment at which values are captured. Avoid adding calculation code unless you understand the workbook’s calculation design.
A version backup preserves state. It is not automatically a validated or reconciled report.
🔒 Protect the VBA project appropriately
You can lock a VBA project for viewing in the VBA editor, which may discourage casual changes. This is not strong security and should not be treated as protection for sensitive code or data.
The more meaningful controls are folder permissions, approved storage, least-privilege access, and a clear process for changing shared tools. If passwords or confidential data are stored in the workbook, reconsider whether the workbook should contain them at all.
Also communicate what the macro does. Users should know where copies go, how long they remain, and who can access them.
🧠 Do not confuse backup with security or compliance
A backup copy protects against accidental editing, corruption, or an unfortunate save. It does not prevent unauthorized access, ransomware, deliberate deletion by someone with permissions, or loss of every copy stored in the same compromised location.
For critical files, use multiple layers: managed storage, access controls, separate backups, and documented recovery procedures. VBA is valuable because it automates a local workflow, not because it solves every information-management risk.
🛠️ Add a manual backup button as a complement
Automatic copies cover routine saving, while a manual button lets users mark a milestone before a major scenario change. Assign CreateVersionBackup to a shape or Form Control button on a clearly labelled worksheet.
A manual button is also useful when you decide not to run the code on every save. Name it plainly, such as Create Backup Version, rather than implying that it saves the active workbook.
Keep the automated and manual routes calling the same central procedure. One source of backup logic means fewer mismatched behaviors to maintain.
🧩 Common mistakes that weaken the system
- Putting the event procedure in a standard module: it will not fire automatically there.
- Saving as .xlsx: the VBA project is removed when Excel warns about incompatible features.
- Using a shared folder for cleanup: a broad deletion rule can remove unrelated files.
- Forgetting error cleanup: Excel events may stay disabled after an error.
- Using only the date in filenames: multiple same-day saves overwrite one another.
- Assuming a copy equals a tested recovery: open a sample backup and verify it.
Most failures are not advanced programming problems. They are assumptions about paths, permissions, file naming, and what users will do under pressure.
📋 A practical implementation checklist
- Save the primary workbook as an
.xlsmfile in a trusted working location. - Insert the BeforeSave event into ThisWorkbook.
- Add the backup and helper procedures to a standard module.
- Use a dedicated backup folder outside the normal working view.
- Test copy creation and restoration with a disposable file.
- Set a retention period that fits the workbook and any organisational rules.
- Document the location and recovery steps for the people who rely on the workbook.
Once it is working, revisit the design after a few weeks. The right number of saved versions is revealed by actual use, not by a default number in code.
✅ The core principle: recoverability beats cleverness
A good Excel VBA backup system is not defined by the longest macro. It is defined by whether someone can quickly find a dated copy, understand what it is, and safely restore it when a mistake is discovered.
Use clear folders, sortable timestamps, narrow cleanup rules, and error handling that restores Excel to a healthy state. Then test recovery before the system is needed. Those choices make the automation dependable rather than merely impressive.
The best version-history routine is one that quietly creates recoverable copies without making ordinary Excel work harder. Start small, test thoroughly, and let the complexity of the workbook determine how far you extend it. ⚙️🗂️🛟

