We all know that making backups of your work is important. Now you can have a macro do it for you. This simple macro can backup your workbook with today's date as part of the file name in the Same folder.
Create a Backup of a Workbook with Current Date
'---------------- Modules ---------------- Sub BackupWorkbook() 'Step 1: Create a Backup of a Workbook with Current Date in the Same folder ThisWorkbook.SaveCopyAs _ FileName:=ThisWorkbook.path & "\" & _ Format(Date, "mm-dd-yy") & " " & _ ThisWorkbook.Name End Sub
How This Macro Works
The trick to this macro is piecing together the new file name. The new file name has three pieces: the path, current date, and the original file name.
You’ll notice that we are formatting the date (Format(Date, "mm-dd-yy")). This is because by default, the Date function returns mm/dd/yyyy. We use hyphens instead of forward slashes because the forward slashes would cause the file save to fail. (Windows does not allow forward slashes in filenames.)
The last piece of the new filename is the original filename. We use the Name property of the
ThisWorkbook object to capture that.
In the one and only step, the macro builds a new filename and uses the SaveCopyAs method to save the file in the Same folder.
Most VBA code should be placed in Standard Modules unless specified.
If you see a comment
'------------------ Modules------------------ in the code header that means put the code in a Standard Module. For more information, learn this course: Where should I put the Excel VBA code?
The following steps teach you how to put VBA code into a Standard Module:
- Activate the Visual Basic Editor by pressing ALT + F11.
- Right-click the project/workbook name in the Project Window.
- Choose Insert -> Module.
- Type or paste the code in the newly created module. You will probably need to change the sheet name, the range address, and the save location.
- Click Run button on the Visual Basic Editor toolbar.
- For more information, learn this course: Programming with Excel VBA