by Allen Wyatt
(last updated August 2, 2014)
Every time Mathew closes a workbook, he'd like to have Excel create a dated backup of that workbook, meaning that it is saved using a filename that includes the date. Thus, if he saves "AnyWorkbookName," it would save not just under that name, but also under the name "AnyWorkbookName [Today's Date & Time]." Mathew is sure this needs to be done with VBA, but he's not sure how to go about it.
There are any number of macros that could be developed to perform this task. Most all of them are variations on a theme (so to speak), so for our purposes a single example should suffice.
The following macro will, just before closing the workbook, save the workbook with a date and time appended to the end of the filename.
Private Sub Workbook_BeforeClose(Cancel As Boolean) Dim sFileName As String Dim sDateTime As String With ThisWorkbook sDateTime = " (" & Format(Now, "yyyy-mm-dd hhmm") & ").xlsm" sFileName = Application.WorksheetFunction.Substitute _ (.FullName, ".xlsm", sDateTime) .SaveCopyAs sFilename End With End Sub
The macro puts together the date and time string into the sDateTime variable. This is then inserted into the workbook's filename by using the SUBSTITUTE worksheet function. (The date/time string is effectively inserted just before the filename extension.) The macro assumes that the workbook is being saved as an XLSM file because it must contain macros—such as the macro to do this saving.
The macro should be placed in the ThisWorkbook module for the workbook. This ensures that it will execute just before the workbook is closed.
There are, as well, third-party add-ins which can perform this task. The following are a few that you may want to check out.
ExcelTips is your source for cost-effective Microsoft Excel training. This tip (13195) applies to Microsoft Excel 2007, 2010, and 2013.
Program Successfully in Excel! John Walkenbach's name is synonymous with excellence in deciphering complex technical topics. With this comprehensive guide, "Mr. Spreadsheet" shows how to maximize your Excel experience using professional spreadsheet application development tips from his own personal bookshelf. Check out Excel 2013 Power Programming with VBA today!
Need to save a workbook in more than one location? Here's a handy macro that can save your workbook in lots of different ...Discover More
If you open a workbook and notice that Excel displays two windows for it, this has to do with how the workbook was saved. ...Discover More
Workbooks are loaded from disk files, but workbooks aren't the only type of files that Excel can load. This tip provides ...Discover More
Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.