Microsoft Office 2000/Visual Basic Programmer's Guide |
When you raise an event, you cause its event procedure to run. For the built-in events you're accustomed to working with, this is the job of the application; for example, when you click a button on a form in a Microsoft Access application, VBA in Access calls the button's Click event procedure and runs any code that's in it. However, when you create a custom event, the application doesn't know when your event is supposed to occur; you have to specify that in your code. Then you — or other developers who are using your custom object — have to create the event procedure and write the code that runs when the event is raised.
The most important thing to understand about custom events is that your code has to cause them to occur. They don't automatically occur in response to something that the user or system does, although you can write code that does cause an event to occur in this manner. The class module that contains a custom event must also include a public method that raises the event. This method raises the event by calling the RaiseEvent statement and passing in any arguments defined for the event. These arguments are in turn passed in to the event procedure that runs in response to the event.
In order for the event to occur, some code outside the class module must call the method that raises the event. For example, code in a form that runs when a command button is clicked might create a new instance of the custom class, assign it to an object variable that has been declared by using the WithEvents keyword, and then call the method that raises the event. When the event occurs, the event procedure in the form's module runs, if the event procedure exists.
Of course, an event can occur without any code responding to it. Events are occurring all the time, in the operating system and in your applications, and code runs in response to some events but not to others. To run code in response to an event that is occurring in an instance of a class, you must create an event procedure that is associated with that instance, as described in "Creating Custom Events" later in this chapter.