Events refer to the actions which gets triggered based on certain tasks. Microsoft Word has many events which can be classified into two major categories, I am trying to list based on usage, If you need detail list of events please follow the link here:
- Application Level
- Application Quit
- Document Level
Since given list of events are predefined for their actions developed by Microsoft. What if user wants to control the behavior of these events?
Microsoft offers custom event programming with the help of VBA by which we can control the behavior of these events. Let’s see some practical work to understand how we can accomplish it
To build custom event solution, we would require followings in place:
- A Class Module: this module will have definition written to our events
- A Standard Module: This is the module where we will instantiate our Class object and subscribe the event
Code Example: Add a new class module and name it “EventClassModule“, Write following code in General section:
Public WithEvents appWord As Word.Application
Define following procedures within class module body:
Private Sub appWord_DocumentBeforeClose(ByVal doc As Document, Cancel As Boolean) 'do whatever you want here... End Sub Private Sub appWord_DocumentBeforeSave(ByVal doc As Document, SaveAsUI As Boolean, Cancel As Boolean) 'do whatever you want here... End Sub Private Sub appWord_Quit() 'do whatever you want here... End Sub
Code Example: Insert standard module and name it as “mdlEventConnect“, write followings in general section to extend the reference of the class:
Dim x As New EventClassModule
Public Sub Register_Event_Handler() Set x.appWord = Word.Application End Sub
That’s it, if you try to perform actions like (DocumentClose, DocumentSave, ApplicationQuite) in your current document, you will be able to see behavior set under the body of the procedures in class modules.
Please leave your valuable comments!!!