Trapping EventsA powerful capability built in to class modules is the ability to respond to events. We want to extend our Analysis application so that when you double-click a cell that has been analyzed, all the cells of the same type will be highlighted. When you right-click the cell, the highlight will be removed. We also want to ensure that cells are reanalyzed when they are changed so that our corresponding Cell objects are kept up to date. The code shown in this section is contained in the Analysis4.xls workbook in the \Concepts\Ch07Using Class Modules to Create Objects folder on the CD that accompanies this book.To trap the events associated with an object you need to do two things:Declare a WithEvents variable of the correct object type in a class module.Assign an object reference to the variable. The events we want to trap are associated with the Worksheet object. Therefore, we need to create a WithEvents object variable in the CCells class module that references the worksheet containing the Cell objects. The appropriate WithEvents variable declaration is made at the module-level within the CCells class and looks like the following: As soon as you add this variable declaration to the CCells class module, you can select the WithEvents variable name from the drop-down menu at the top left of the module and use the drop-down menu at the top right of the module to see the events that can be trapped, as shown in Figure 7-1. Event names listed in bold are currently being trapped within the class, as you will see in a moment. Figure 7-1. The Worksheet Event Procedures Available in CCells[View full size image] ![]() Listing 7-11. Additions to the CCells Class ModuleThe CreateCellsCollection procedure in the MEntryPoints module needs to be changed as shown in Listing 7-12. The new code assigns a reference to the active worksheet to the Worksheet property of the Cells object so the worksheet's events can be trapped. Listing 7-12. The Updated CreateCellsCollection Procedure in the MEntryPoints ModuleYou can now execute the CreateCellsCollection procedure in MEntryPoints to create a new collection with all the links in place to trap the double-click and right-click events for the cells in the worksheet. Double-clicking a cell changes the cell's background of all similar cells to a color that depends on the cell's type. Right-clicking a cell removes the background color. |