XL97: How to Create Application Level Event HandlersLast reviewed: March 13, 1998Article ID: Q158244 |
The information in this article applies to:
SUMMARYIf you want a particular event handler to run whenever a certain event is triggered, you can write an event handler for the Application object. Event handlers for the Application object are global, which means that as long as Microsoft Excel is open, the event handler will run when the appropriate event occurs, regardless of which workbook is active when the event occurs. This article describes how to create an Application level event handler and provides an example.
MORE INFORMATIONTo create an Application-level event handler, you must use the following basic steps: - Declare a variable for the Application object using the WithEvents keyword. The WithEvents keyword can be used to create an object variable that responds to events triggered by an ActiveX object (such as the Application object).NOTE: WithEvents is valid only in a class module. - Create the procedure for the specific Application event. For example, you could create a procedure for the WindowResize, WorkbookOpen, or SheetActivate event of the object you declared using WithEvents.- Create and run a procedure that starts the event handler. The following example uses these steps to set up a global event handler that displays a message box whenever you resize any workbook window (the event firing the event handler).
Creating and initiating the event handler
Private Sub appevent_WindowResize(ByVal Wb As Excel.Workbook, _ ByVal Wn As Excel.Window) End Sub Public WithEvents appevent As Application Private Sub appevent_WindowResize(ByVal Wb As Excel.Workbook, _ ByVal Wn As Excel.Window) MsgBox "you resized a window" End SubNext, you have to create an instance of the class and then set the appevent object of the instance of the Class1 to Application. This is because when you declare a variable, WithEvents, at design time, there is no object associated with it. A WithEvents variable is just like any other object variable - you have to create an object and assign a reference to the object to the WithEvents variable.
How to turn off the event handlerIf you close the workbook that contains the above project, the application level event handler will be turned off. To programmatically turn off the event handler, do the following:
REFERENCESFor more information about Class Modules, in the Visual Basic Editor click "Contents and Index" on the Help menu, click the Index tab, type the following text
class moduleand then double-click the selected text to go to the "Module and Class Module Commands (Insert Menu)" topic.
|
Additional query words: vbe 8.00 XL97
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |