|
Microsoft Office Application Development
|
|
Handling Worksheet control events using a class module. Hooking up the controls to the class moduleNow that the event sub is in place the blueprint code is ready. All that needs to be done now is to hook up the controls on the worksheet to the class module. First we'll write some code in the class module that will receive the object it is going to "listen" to from an initialisation routine I'll show later: Public Property Set Control(obtNew As MSForms.OptionButton) Now we need to create just as many instances of this class module as
there are controls to hook up and tie each control to its own instance of the
class module. Insert a normal module in the project. Dim mcolEvents As Collection Then we'll loop through all OLEObjects on the worksheet and hook up the Optionbutton controls to the event, here is the code for the entire module: Option Explicit The final step is to make sure the InitializeEvents code gets run at e.g. Workbook_Open (in the ThisWorkbook module): Option Explicit Shutting down and tidying upWhen the workbook is closed, or you want to stop the class from responding to events, you also need code to clean up when the class is terminated: Private Sub Class_Terminate() This ensures the memory that is holding the control object reference is freed once the class is set to nothing: (in a normal module) Sub TerminateEvents() If you step to the above sub, you will see that the Class_Terminate subroutine will be run for each instance of the class as has been created in the subroutine "InitialiseEvents". Of course you want this sub to run when your workbook closes, so in the ThisWorkbook module, add: Private Sub Workbook_BeforeClose(Cancel As Boolean)
| ||||||||||||||
Use the contact page to issue
questions or comments about this website. |