Home > Articles > Home & Office Computing > Microsoft Applications

This chapter is from the book

Automatically Saving Your Work Frequently

Setting the AutoRecover interval to 1 minute, as described in the previous section, is probably good enough for most people. However, a fast typist can easily write dozens of words in a minute, so you can still lose a fair amount of work even when using the shortest AutoRecover interval.

To get an even faster save interval, you can use VBA, specifically, Word's OnTime method, which runs a procedure at a specified time. The OnTime method uses the following syntax:

Application.OnTime(When, Name [, Tolerance])

When

The time (and date, if needed) you want the procedure to run.

Name

The name of the procedure to run when the time given by When arrives.

Tolerance

If Word isn't ready to run the procedure at When, it will keep trying for the number of seconds specified by Tolerance. If you omit Tolerance, VBA waits until Word is ready.

You must enter the When argument as a date/time serial number. The easiest way to do this is to use the TimeValue function:

TimeValue(Time)

Time

A string representing the time you want to use (such as "8:00 PM" or "20:00").

For example, the following code runs a procedure called MakeBackup at 8:00 PM:

Application.OnTime _
    When:=TimeValue("8:00 PM"), _
    Name:="MakeBackup"

What we really want to do here is run a macro that saves the current document, and we want to run that macro at a specified time interval (for example, every 30 seconds). If you want the OnTime method to run after a specified time interval, use the expression Now + TimeValue(Time) for When (where Time is the interval you want to use). For example, if you want to save your work every 30 seconds, use the following expression for When:

Now + TimeValue("00:00:30"),

Listing 3.1 shows a macro that does this.

Listing 3.1. A Macro That Saves the Active Document Every 20 Seconds

Public Sub FileSave()
    ActiveDocument.Save
    DoEvents
    Application.OnTime _
        When:=Now + TimeValue("00:00:20"), _
        name:="FileSave"
    Application.StatusBar = "Saved: " & ActiveDocument.Name
End Sub

The FileSave macro begins by saving the current document using the ActiveDocument object's Save method. The DoEvents method processes any keystrokes that occurred during the save, and then the OnTime method sets up the FileSave procedure to run again in 20 seconds. The macro ends by displaying a status bar message to let you know the document was saved.

  • + Share This
  • 🔖 Save To Your Account