A Pseudo DocumentBeforeClose Event

Or: How to perform validation on a document when the user tries to close it, before the user is asked to save changes

Article contributed by Ibby

There is no DocumentBeforeClose event in Word97. Even in Word 2000, there are serious problems with using the DocumentBeforeClose application event, in that if the user quits Word using File + Exit, the DocumentBeforeClose event fires after the messages asking whether you want to save changes, instead of before!! This bug makes the DocumentBeforeClose event useless if you want to validate anything before the save changes message appears.

However, you can create a  fakeDocumentBeforeClose event, in either version of Word – which does always fire before the the save changes message appears – as follows:

The code needs to be in the Document_Close event procedure (ThisDocument module) or in a macro named AutoClose in a normal code module so that it runs when the user tries to close the document. The code needs to do the following:

So, the following code will prevent the user from being able to close the document:

Public Sub AutoClose()

   ' Mark the document as unsaved so a prompt
   ' appears asking whther to save changes.

   ActiveDocument.Saved = False

   ' Dismiss the displayed prompt.

   SendKeys "{ESC}"

End Sub

To use this in a validation routine, just wrap this in the validation code. The following example prevents closing of the document if it contains more than three paragraphs:

Public Sub AutoClose()

If ActiveDocument.Paragraphs.Count > 3 Then
    ' If there are more than 3 paragraphs in document,
    ' display a msg to user.

    MsgBox "You are not allowed more than 3 paragraphs."

    ' Then cancel closing of the document.
    ' Mark the document as unsaved so a prompt
    ' appears asking whether to save changes.

    ActiveDocument.Saved = False

    ' Dismiss the displayed prompt.

    SendKeys "{ESC}"
End Iff

End Sub