VBScript – Backup a File and add a Date Time Stamp

In an Access forum a user was asking how they could make an automated backup of their database.

Their are a number of possible solutions, including:

  • If your IT department already performs routine backups, simply ask them to add your database to their backups
  • You could install a backup program yourself

Another viable solution is to create a simple Batch file (*.bat) of VBScript file to perform the backup and then use the Windows Task Scheduler to run it on the basis of your choice (typically nightly).  To help you get this process setup and running, below are 2 VBScripts to perform the backup of the database file.

Simple File Copy

'Author: Daniel Pineault
Dim objFSO
Dim sSourceFolder
Dim sDestFolder
Dim sDBFile
Const OVER_WRITE_FILES = True

Set objFSO = CreateObject("Scripting.FileSystemObject")
sSourceFolder = "C:\Databases\Test"
sBackupFolder = "C:\Users\Daniel\Desktop\New folder (3)"
sDBFile = "Test.mdb"

'If the backup folder doesn't exist, create it.
If Not objFSO.FolderExists(sBackupFolder) Then
    objFSO.CreateFolder(sBackupFolder)
End If

'Copy the file as long as the file can be found
If objFSO.FileExists(sSourceFolder & "\" & sDBFile) Then
    objFSO.CopyFile sSourceFolder & "\" & sDBFile, sBackupFolder & "\" & sDBFile, OVER_WRITE_FILES
End if

Set objFSO = Nothing

File Copy with the Addition of a Date/Time Stamp

'Author: Daniel Pineault
Dim objFSO
Dim sSourceFolder
Dim sDestFolder
Dim sDBFile
Dim sDateTimeStamp
Const OVER_WRITE_FILES = True

Set objFSO = CreateObject("Scripting.FileSystemObject")
sSourceFolder = "C:\Databases\Test"
sBackupFolder = "C:\Users\Daniel\Desktop\New folder (3)"
sDBFile = "Test"
sDBFileExt = "mdb"
sDateTimeStamp = cStr(Year(now())) & _
                 Pad(cStr(Month(now())),2) & _
                 Pad(cStr(Day(now())),2) & _
                 Pad(cStr(Hour(now())),2) & _
                 Pad(cStr(Minute(now())),2) & _
                 Pad(cStr(Second(now())),2)

'If the backup folder doesn't exist, create it.
If Not objFSO.FolderExists(sBackupFolder) Then
    objFSO.CreateFolder(sBackupFolder)
End If

'Copy the file as long as the file can be found
If objFSO.FileExists(sSourceFolder & "\" & sDBFile & "." & sDBFileExt) Then
    objFSO.CopyFile sSourceFolder & "\" & sDBFile & "." & sDBFileExt,_
                    sBackupFolder & "\" & sDBFile & "_" & sDateTimeStamp & "." & sDBFileExt,_
                    OVER_WRITE_FILES
End if

Set objFSO = Nothing


Function Pad(CStr2Pad, ReqStrLen)
'Source: http://saltwetbytes.wordpress.com/2012/10/16/vbscript-adding-datetime-stamp-to-log-file-name/
    Dim Num2Pad

    Pad = CStr2Pad
    If len(CStr2Pad) < ReqStrLen Then
        Num2Pad = String((ReqStrlen - Len(CStr2Pad)), "0")
        Pad = Num2Pad & CStr2Pad
    End If
End Function

Usage

In either case, you simply create a new text file (give it whatever name you want) but give it a file extension of vbs and copy/paste the code from above (adjusting the values of the necessary variables to reflect your files/folders). Then simply double-click to run it.

As always, when trying new code be sure to make backup copies of your files!

Other Considerations

These scripts could easily be further enhanced by adding checks to validate that the specified files/folders exist. We could test for the presence of a lock file, if we're talking about Access databases... We could generate a log file of the process...

Per usual, the sky is the limit. This is a simple example, but you can easily customize it and make it your own!

17 responses on “VBScript – Backup a File and add a Date Time Stamp

  1. Daniel Pineault Post author

    Why would you use an external site to generate a date/timestamp when you can so easily do it yourself with a few lines of code? Beyond which by porting it to a third-party website, you open yourself to a security risk since you have no clue what the site might, or might not, be exposing your browser to. Lastly, my code runs in milliseconds, your technique will take seconds (or longer) because you need to open a browser, connect to the site, populate controls, submit your request, wait for the reply for the site, …

    Not the way I have, or would, ever do things.

  2. Declan Cunningham

    Thanks that works brilliantly,
    Is it possible to add an underscore between the day Month year to make it more readable?

    1. Daniel Pineault Post author

      You should simply need to tweak the sDateTimeStamp variable to something like

      sDateTimeStamp = cStr(Year(now())) & "_" & _
                       Pad(cStr(Month(now())),2) & "_" & _
                       Pad(cStr(Day(now())),2) & _
                       Pad(cStr(Hour(now())),2) & _
                       Pad(cStr(Minute(now())),2) & _
                       Pad(cStr(Second(now())),2)

      As you can see, all you should need to do is concatenate in a string underscore by adding & “_” to the code between each segment. You could continue the idea and add an underscore everywhere which would result in

      sDateTimeStamp = cStr(Year(now())) & "_" & _
                       Pad(cStr(Month(now())),2) & "_" & _
                       Pad(cStr(Day(now())),2) & "_" & _
                       Pad(cStr(Hour(now())),2) & "_" & _
                       Pad(cStr(Minute(now())),2) & "_" & _
                       Pad(cStr(Second(now())),2)
  3. Jeff

    Is there a way to modify this to backup multiple files in a folder to another folder and add the date?

  4. Ray Worth

    Used as a function called by an Autoexec macro. Works perfectly. Many thanks -much appreciated.

  5. Gosh

    I need your help
    It does not work for me.
    Plz check the following Codes

    ‘Author: Daniel Pineault
    Dim objFSO
    Dim sSourceFolder
    Dim sDestFolder
    Dim sDBFile
    Const OVER_WRITE_FILES = True

    Set objFSO = CreateObject(“Scripting.FileSystemObject”)
    sSourceFolder = “C:\Databases\Test”
    sBackupFolder = “C:\Users\DELL\Desktop\new folder (3)”
    sDBFile = “Test.mdb”

    ‘If the backup folder doesn’t exist, create it.
    If Not objFSO.FolderExists(sBackupFolder) Then
    objFSO.CreateFolder(sBackupFolder)
    End If

    ‘Copy the file as long as the file can be found
    If objFSO.FileExists(sSourceFolder & “\” & sDBFile) Then
    objFSO.CopyFile sSourceFolder & “\” & sDBFile, sBackupFolder & “\” & sDBFile, OVER_WRITE_FILES
    End if

    Set objFSO = Nothing

    1. Daniel Pineault Post author

      Doesn’t work, doesn’t give me much to go on to try and help you. What happens exactly? Do you get any messages? Do the folders exists? You have permissions to both folders (you can create, edit, save and delete in both)?

    2. Jim McFadden

      I copied and pasted your code into VSCode, and after fixing the quote marks, and changing the paths to match my file system, pasted it into an Access Macro (Sub.) If running the macro Option Explicit, the sub will pop an error: Compile Error: Variable not defined. Specifically referring to sBackupFolder. sBackupFolder was not declared at the beginning of the module. Rather, sDestFolder is declared. This is exactly as posted by the OP. Without the Option Explicit statement, the code worked exactly as you posted it. Running it a second time, over wrote the file, exactly as stated: OVER_WRITE_FILES.

      Running the script stand-alone, the script worked exactly as expected, as stated above. The improper variable declaration and use, had no affect on the process. It should be noted though, that this is a very poor programming practice. The OP mostly likely simply copied and pasted the code, but failed to proof it first–under more than one scenario, if that.

      For further investigation: Look for logical errors–Check the file extension, and that your paths are correct. Logical errors, in general, will not throw error messages or indication, other than a failure to work. GiGo: Garbage in Garbage out. Third parties usually, cannot trace or fix logical errors, without sitting at your computer. Also, perhaps it is just here, but without proper indentation, code is harder to read and debug.

      JM, B.S.

      1. Daniel Pineault Post author

        The improper variable declaration and use, had no affect on the process. It should be noted though, that this is a very poor programming practice.

        Although I appreciate your enthusiasm, in this case it is misguided. As the title of the page indicates, this code was created for use as a VBScript and VBScript does not have variable type declarations like VBA does. Obviously, if one is trying to port this to VBA, then yes, adding variable types would be best. Then again, I already have VBA backup examples on the site, better just use one of them instead.

  6. Ahsen Javaid

    Hi I need some informationa about:
    I am noob at VBA or VB, I just want to know where to paste this script? In MS Access Module and If I save it in MS Access module how should I run that module?

    1. Jim Mcfadden

      Yes, the code will run from a macro or module in M.S. Access, Run as a Function, or Sub. However, backing up an open database ( or any open file) may have unexpected results. The code will also run in a VBScript file, “filename.vbs.”

  7. Angel Stanhope

    Hi
    I have the code running and a backup is produced (using the OnLoad for the ‘Display Form’) , however, when opening the copied backup file I get this message:
    If ‘AutoExec’ is a new macro or macro group, make sure you have saved it and that you have typed its name correctly.
    The Navigation Pane is empty, nothing displayed. Please help.

    1. Daniel Pineault Post author

      Normally, we never make a backup of a file we are actively in as it can lead to corruption.

      I don’t know what code you are using, nor have I seen the output file, so I truly don’t know where to start. I’d urge you to post your question in a forum and give as many details as you can (error message, error number, code used to produce the backup, corrupted backup if you can).