Understanding Custom Events
When you raise an event, you cause its event procedure to run. For the built-in events you are 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, Microsoft® Visual Basic® for Applications (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 does not 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 do not 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.
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.
Why Build Your Own Objects? | Basic Class Concepts | Creating Property Procedures | Creating Events and Event Procedures | Extending Objects Through Interfaces | Designing Object Models | Creating Custom Objects for Web Pages | Creating Custom Events