Sie sind auf Seite 1von 10

Backup a Data Base Using a VBScript

(A) Code can be obtained from the Reference (1) or at Appendix – Code 1

Instructions

1. Copy/Paste the code into a new blank text file


2. Name the file
3. Change the 4 input variable so they are configured for your setup (path, filename, …)
4. Modify the Call Backup(…) to apply the settings you desire (force copy, silent, compact)
5. Save
6. Change the text file’s extension from txt to vbs
7. Run the VBScript by double-clicking on it (For Manual Operation)

(B) Creating Your Windows Automation Rule

Using Windows Applications available on your PC, Windows Task Scheduler, Notepad and CScript
(Located: C:\Windows\System32\cscript.exe) to auto run a .vbs file.

Finally, we will create an automation rule (or task) using a native Windows application called
Windows Task Scheduler. To find this hidden gem, just type “Windows Task Scheduler” in the
search bar of your Taskbar and launch it.

You should see a Task Scheduler dialog appear that looks something similar to the image below. If
you do not see the Actions pane to the right, click the last icon in the application’s toolbar.

1. To create a new task, simple click “Create Task”

2. Create Task – General Tab


In the General Tab, you will be able to provide a name and a description (optional) for your
automation task. Make sure to make your name descriptive so it will be easy to find in the long list of
tasks that other applications on your PC have already created.

You will also be able to determine you would like the task to run if you are logged in/out of your PC. I
assume most of you will want to enable the task to run while your computer is logged off, especially
if your task is running on off hours.

3. Create Task – Triggers Tab

In the Triggers Tab, you will be able to create in-depth scheduling rules for your automation. In the
below example, I am creating a Trigger to execute the Task every day at 6:30am.

There are also options in the Advanced Settings section to repeat the task after the initial trigger. For
example, you may what to refresh a stock portfolio model every 10 minutes after the stock market
opens. The Advanced Settings section gives you the freedom to repeat the task every X number of
minutes after the initial trigger has executed.

You do have the freedom to create multiple trigger rules if necessary.


4. Create Task – Action Tab

The Actions Tab is where you will map out which program you would like to launch. In our example,
we are going to want to run the .vbs file we created that will open and run our Excel macro. We will
utilize a program called CScript to execute our .vbs file. You should have this program already
installed if you have a Windows OS. Below is the path to the application for your reference:

Program/Script: "C:\Windows\System32\cscript.exe"

Next, we will want to reference the file to open via CScript. Paste in the full file path of the .vbs file
we created earlier. Mine looks something like this:

Add Arguments: "C:\Users\chris\Documents\Macro Launcher.vbs"

PLEASE NOTE: Both of these inputs MUST be surrounded by double quotation marks or else your
task will not function!

5. Create Task – Settings Tab

Finally, the Settings tab provides a few additional options to customize your task. I have highlighted
one important option below if you are incorporating a “completion notification” message box into
your Visual Basic script (FYI we are using a message box in the example).

It is important to understand that if a message box appears on the screen, by default your task
cannot repeat itself until the message box is closed by the user. To get around this, you can tell the
task to kill itself if and rerun if no one ended up closing the message box during the time between
triggers.
(C) Vbscript to delete backup files more than XX days old

Instructions

1. Copy/Paste the code into a new blank text file


2. Name the file
3. Change the 3 input variable so they are configured for your setup (path, number of days and
type of file with number of character in the file extension)
4. Save
5. Change the text file’s extension from txt to vbs
6. run the VBScript by double-clicking on it (For Manual Operation)

References
1. https://www.devhut.net/2018/02/22/ms-access-backup-a-database-using-a-vbscript/
2. https://www.thespreadsheetguru.com/blog/how-to-automatically-run-excel-vba-macros-
daily
3. https://www.symantec.com/connect/downloads/vbscript-delete-old-files
Appendix 1 – VBScript Code for Backup
'----------------------------------------------------------------------
-----------------
' Author : Daniel Pineault, CARDA Consultants Inc.
' Website : http://www.cardaconsultants.com
' Purpose : Backup an Access Database
' Copyright : The following is release as Attribution-ShareAlike 4.0
International
' (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-
sa/4.0/
'
' Revision History:
' Rev Date(yyyy/mm/dd) Description
'
***********************************************************************
***************
' 1 2018-02-22 Initial Release
'----------------------------------------------------------------------
-----------------
Dim sSourceFolder
Dim sBackupFolder
Dim sDBFile
Dim sDBFileExt

'Set our required variables


sSourceFolder = "C:\Users\Daniel\Desktop"
sBackupFolder = "C:\Users\Daniel\Desktop\DBBackup"
sDBFile = "WebBrowser_Image_Demo"
sDBFileExt = "accdb"
'Run the backup procedure
Call BackupDb(sSourceFolder, sBackupFolder, sDBFile, sDBFileExt, True,
True, True)

'----------------------------------------------------------------------
-----------------
'----------------------------------------------------------------------
-----------------
'
***********************************************************************
***************
'
***********************************************************************
***************
' You shouldn't need to edit anything below this point normally, so
be careful!
'
***********************************************************************
***************
'
***********************************************************************
***************
'----------------------------------------------------------------------
-----------------
'----------------------------------------------------------------------
-----------------
'----------------------------------------------------------------------
-----------------
' Procedure : BackupDb
' Author : Daniel Pineault, CARDA Consultants Inc.
' Website : http://www.cardaconsultants.com
' Purpose : Database Backup Routine
' Copyright : The following is release as Attribution-ShareAlike 4.0
International
' (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-
sa/4.0/
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sSourceFolder : Folder in which the database resides ->
"C:\Temp\Databases"
' sBackupFolder : Folder where the backups should be saved ->
"C:\Temp\Databases\Backups"
' sDBFile : Filename of the database to backup ->
"TestDatabase"
' sDBFileExt : Extension of the database to backup -> "accdb"
' bForceCopy : Should the backup be performed if a lock file is
present -> True/False
' bRunSilent : Should Messages be displayed when the procedure is run
-> True/False
' bCompact : Should the backup datbase be automatically
compacted -> True/False
'
' Revision History:
' Rev Date(yyyy/mm/dd) Description
'
***********************************************************************
***************
' 1 2018-02-22 Initial Release
'----------------------------------------------------------------------
-----------------
Function BackupDb(sSourceFolder, sBackupFolder, sDBFile, sDBFileExt,
bForceCopy, bRunSilent, bCompact)
Dim oFSO
dim sDBLockFileExt

Select Case sDBFileExt


case "mdb", "mde"
sDBLockFileExt = "ldb"
case "accdb", "accde", "accdr"
sDBLockFileExt = "laccdb"
End select

Set oFSO = CreateObject("Scripting.FileSystemObject")

'Validate that the file actually exists


If oFSO.FileExists(sSourceFolder & "\" & sDBFile & "." &
sDBFileExt) = False Then
If bRunSilent=False Then
Msgbox "The specified database file '" &
sSourceFolder & "\" & sDBFile & "." & sDBFileExt & "' cannot be
loacted.", _
vbCritical or vbOKOnly, "Operation
Aborted"
End If
Else
If bForceCopy = True Then
'Backup the file
Call CopyFile(oFSO, sSourceFolder, sBackupFolder,
sDBFile, sDBFileExt, bCompact)
Else
'Check for the presence of a lock file
If oFSO.FileExists(sSourceFolder & "\" & sDBFile
& "." & sDBLockFileExt) = True Then
Msgbox "There is currently a lock file
present. Cannot perform the backup at this time", _
vbCritical or vbOKOnly,
"Operation Aborted"
Else
'Backup the file
Call CopyFile(oFSO, sSourceFolder,
sBackupFolder, sDBFile, sDBFileExt, bCompact)
End If
End If
End if

'Cleanup
Set oFSO = Nothing
End Function

'----------------------------------------------------------------------
-----------------
' Procedure : CopyFile
' Author : Daniel Pineault, CARDA Consultants Inc.
' Website : http://www.cardaconsultants.com
' Purpose : Backup the file while appending a date/time stamp to the
filename
' Copyright : The following is release as Attribution-ShareAlike 4.0
International
' (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-
sa/4.0/
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' oFSO : File System Object
' sSourceFolder : Folder in which the database resides ->
"C:\Temp\Databases"
' sBackupFolder : Folder where the backups should be saved ->
"C:\Temp\Databases\Backups"
' sDBFile : Filename of the database to backup ->
"TestDatabase"
' sDBFileExt : Extension of the database to backup -> "accdb"
' bCompact : Should the backup datbase be automatically
compacted -> True/False
'
' Revision History:
' Rev Date(yyyy/mm/dd) Description
'
***********************************************************************
***************
' 1 2018-02-22 Initial Release
'----------------------------------------------------------------------
-----------------
Function CopyFile(oFSO, sSourceFolder, sBackupFolder, sDBFile,
sDBFileExt, bCompact)
Dim sDateTimeStamp
Const OVER_WRITE_FILES = True

'Build the date/time stamp to append to the filename


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 oFSO.FolderExists(sBackupFolder) Then
oFSO.CreateFolder(sBackupFolder)
End If

'Copy the file as long as the file can be found


oFSO.CopyFile sSourceFolder & "\" & sDBFile & "." & sDBFileExt,_
sBackupFolder & "\" & sDBFile & "_" &
sDateTimeStamp & "." & sDBFileExt,_
OVER_WRITE_FILES

If bCompact = True Then


Call CompactDB(sBackupFolder & "\" & sDBFile & "_" &
sDateTimeStamp & "." & sDBFileExt)
End If
End Function

'----------------------------------------------------------------------
-----------------
' Procedure : CompactDB
' Author : Daniel Pineault, CARDA Consultants Inc.
' Website : http://www.cardaconsultants.com
' Purpose : Compact the specified database file
' Copyright : The following is release as Attribution-ShareAlike 4.0
International
' (CC BY-SA 4.0) - https://creativecommons.org/licenses/by-
sa/4.0/
'
' Input Variables:
' ~~~~~~~~~~~~~~~~
' sFile : Database file (path & full filename with extension) to
compact
'
' Revision History:
' Rev Date(yyyy/mm/dd) Description
'
***********************************************************************
***************
' 1 2018-02-22 Initial Release
'----------------------------------------------------------------------
-----------------
Function CompactDB(sFile)
Dim oWshShell
Dim sAppEXE
Dim sRegKey
Dim sAccessPath

sAppEXE = "MSACCESS.EXE"
sRegKey =
"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App
Paths\" & sAppEXE & "\Path"
Set oWshShell = CreateObject("WScript.Shell")
sAccessPath = oWshShell.RegRead(sRegKey)
oWshShell.Run chr(34) & sAccessPath & sAppEXE & chr(34) & " " &
_
chr(34) & sFile & chr(34) & " /compact", 0, True

Set oWshShell = Nothing


End Function

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

Pad = CStr2Pad
If len(CStr2Pad) < ReqStrLen Then
Num2Pad = String((ReqStrlen - Len(CStr2Pad)), "0")
Pad = Num2Pad & CStr2Pad
End If
End Function
Appendix 2 – VBScript Code for Deleting older Backup files
'************ Start of Code **********************

Option Explicit
On Error Resume Next
Dim oFSO, oFolder, sDirectoryPath
Dim oFileCollection, oFile, sDir
Dim iDaysOld

' Specify Directory Path From Where You want to clear the old files

sDirectoryPath = "C:\Users\SeetohGKH\Desktop\Access Database Backup_Copy"

' Specify Number of Days Old File to Delete

iDaysOld = 10

Set oFSO = CreateObject("Scripting.FileSystemObject")


Set oFolder = oFSO.GetFolder(sDirectoryPath)
Set oFileCollection = oFolder.Files

For each oFile in oFileCollection

'This section will filter the log file as I have used for for test case
'Specify the Extension of file that you want to delete
'and the number with Number of character in the file extension

If LCase(Right(Cstr(oFile.Name), 3)) = "mdb" Then

If oFile.DateLastModified < (Date() - iDaysOld) Then


oFile.Delete(True)
End If

End If
Next

Set oFSO = Nothing


Set oFolder = Nothing
Set oFileCollection = Nothing
Set oFile = Nothing

'**************** End of Code *******************

Das könnte Ihnen auch gefallen