Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

Practical Example

We illustrate the use of class modules in our PETRAS example applications by providing both the Time Sheet and Reporting applications with Excel application-level event handlers.

PETRAS Time Sheet

The addition of an application-level event handling class to our PETRAS time sheet application will make two significant changes. First, it will allow us to convert the time entry workbook into an Excel template. This will simplify creation of new time entry workbooks for new purposes as well as allow multiple time entry workbooks to be open at the same time. Second, the event handler will automatically detect whether a time entry workbook is active and enable or disable our toolbar buttons accordingly. Table 7-1 summarizes the changes made to the PETRAS time sheet application for this chapter.

Table 7-1. Changes to PETRAS Time Sheet Application for Chapter 7





Changes the normal workbook into a template workbook


Adds an application-level event handling class to the add-in



New procedure to create time sheets from the template workbook



Removes time sheet initialization logic and delegates it to the event handling class


Moves all time entry workbook management code into the event handling class

The Template

When a template workbook is added using VBA, a new, unsaved copy of the template workbook is opened. To create a template workbook from a normal workbook, choose File > Save As from the Excel menu and select the Template entry from the Save as type drop-down. As soon as you select the Template option Excel unhelpfully modifies the directory where you are saving your workbook to the Office Templates directory, so don't forget to change this to the location where you are storing your application files.

Once we begin using a template workbook, the user has complete control over the workbook filename. We can determine whether a given workbook belongs to us by checking for the unique named constant "setIsTimeSheet" that we added to our template workbook for this purpose.

A template workbook combined with an application-level event handler allows us to support multiple instances of the time entry workbook being open simultaneously. This might be needed, for example, if there is a requirement to have a separate time sheet for each client or project.

Moving to a template user interface workbook also requires that we give the user a way to create new time sheet workbooks, since it is no longer a simple matter of opening and reusing the same fixed time sheet workbook over and over. In Figure 7-2, note the new toolbar button labeled New Time Sheet. This button allows the user to create new instances of our template.

Figure 7-2

Figure 7-2 The PETRAS toolbar with the New Time Sheet button

As shown in Listing 7-21, the code run by this new button is simple.

Listing 7-21. The NewTimeSheet Procedure

Public Sub NewTimeSheet()
    Application.ScreenUpdating = False
    Application.Workbooks.Add gsAppDir & gsFILE_TIME_ENTRY
    Application.ScreenUpdating = True
End Sub

We turn off screen updating and call InitGlobals to ensure that our global variables are properly initialized. We then simply add a new workbook based on the template workbook and turn screen updating back on. Rather than opening PetrasTemplate.xlt, a new copy of PetrasTemplate.xlt, called PetrasTemplate1 is created. Each time the user clicks the New Time Sheet button she gets a completely new, independent copy of PetrasTemplate.xlt.

The act of creating a new copy of the template triggers the NewWorkbook event in our event handing class. This event performs all the necessary actions to initialize the template. This event procedure is shown in the next section.

The Application-Level Event Handler

Within our application-level event handling class we encapsulate many of the tasks previously accomplished by procedures in standard modules. For example, the MakeWorksheetSettings procedure and the bIsTimeEntryBookActive function that we encountered in Chapter 5, "Function, General, and Application-Specific Add-ins," are now both private procedures of the class.

We describe the layout of the class module and then explain what the pieces do, rather than showing all the code here. You can examine the code yourself in the PetrasAddin.xla workbook of the sample application for this chapter on the CD and are strongly encouraged to do so.

  • Module-Level Variables
  • Private WithEvents mxlApp As Excel.Application
  • Class Event Procedures
  • Class_Initialize
  • Class_Terminate
  • mxlApp_NewWorkbook
  • mxlApp_WorkbookOpen
  • mxlApp_WindowActivate
  • mxlApp_WindowDeactivate
  • Class Method Procedures
  • SetInitialStatus
  • Class Private Procedures
  • EnableDisableToolbar
  • MakeWorksheetSettings
  • bIsTimeEntryBookActive
  • bIsTimeEntryWorkbook

Because the variable that holds a reference to the instance of the CAppEventHandler class that we use in our application is a public variable, we use the InitGlobals procedure to manage it. The code required to do this is shown in two locations.

In the declarations section of the MGlobals module:

Public gclsEventHandler As CAppEventHandler

In the InitGlobals procedure:

' Instantiate the Application event handler
If gclsEventHandler Is Nothing Then
    Set gclsEventHandler = New CAppEventHandler
End If

The InitGlobals code checks to see whether the public gclsEventHandler variable is initialized and initializes it if it isn't. InitGlobals is called at the beginning of every non-trivial entry point procedure in our application, so if anything causes our class variable to lose state, it will be instantiated again as soon as the next entry point procedure is called. This is a good safety mechanism.

When the public gclsEventHandler variable is initialized, it causes the Class_Initialize event procedure to execute. Inside this event procedure we initialize the event handling mechanism by setting the class module-level WithEvents variable to refer to the current instance of the Excel Application, as follows:

Set mxlApp = Excel.Application

Similarly, when our application is exiting and we destroy our gclsEventHandler variable, it causes the Class_Terminate event procedure to execute. Within this event procedure we destroy the class reference to the Excel Application object by setting the mxlApp variable to Nothing.

All the rest of the class event procedures, which are those belonging to the mxlApp WithEvents variable, serve the same purpose. They "watch" the Excel environment and enable or disable our toolbar buttons as appropriate when conditions change.

Disabling toolbar buttons when they can't be used is a much better user interface technique than displaying an error message when the user clicks one under the wrong circumstances. You don't want to punish users (that is, display an error message in response to an action) when they can't be expected to know they've done something wrong. Note that we always leave the New Time Sheet and Exit PETRAS toolbar buttons enabled. Users should always be able to create a new time sheet or exit the application.

In addition to enabling and disabling the toolbar buttons, the mxlApp_NewWorkbook and mxlApp_WorkbookOpen event procedures detect when a time entry workbook is being created or opened for the first time, respectively. At this point they run the private MakeWorksheetSettings procedure to initialize that time entry workbook. All the mxlApp event procedures are shown in Listing 7-22. As you can see, the individual procedures are simple, but the cumulative effect is powerful.

Listing 7-22. The mxlApp Event Procedures

Private Sub mxlApp_NewWorkbook(ByVal Wb As Workbook)
    If bIsTimeEntryWorkbook(Wb) Then
        EnableDisableToolbar True
        MakeWorksheetSettings Wb
        EnableDisableToolbar False
    End If
End Sub

Private Sub mxlApp_WorkbookOpen(ByVal Wb As Excel.Workbook)
    If bIsTimeEntryWorkbook(Wb) Then
        EnableDisableToolbar True
        MakeWorksheetSettings Wb
        EnableDisableToolbar False
    End If
End Sub

Private Sub mxlApp_WindowActivate(ByVal Wb As Workbook, _
                                       ByVal Wn As Window)
    ' When a window is activated, check to see if it belongs
    ' to one of our workbooks. Enable all our toolbar controls
    ' if it does.
    EnableDisableToolbar bIsTimeEntryBookActive()
End Sub

Private Sub mxlApp_WindowDeactivate(ByVal Wb As Workbook, _
                                       ByVal Wn As Window)
    ' When a window is deactivated, disable our toolbar
    ' controls by default. They will be re-enables by the
    ' WindowActivate event procedure if required.
    EnableDisableToolbar False
End Sub

The full power of having an event handling class in your application is difficult to convey on paper. We urge you to experiment with the sample application for this chapter to see for yourself how it works in a live setting. Double-click the PetrasAddin.xla file to open Excel and see how the application toolbar behaves. Create new time sheet workbooks, open non-time sheet workbooks, and switch back and forth between them. The state of the toolbar will follow your every action.

It is also educational to see exactly how much preparation the application does when you create a new instance of the time sheet workbook. Without the PetrasAddin.xla running, open the PetrasTemplate.xlt workbook and compare how it looks and behaves in its raw state with the way it looks and behaves as an instance of the time sheet within the running application.

PETRAS Reporting

By adding a class module to handle application-level events to the PETRAS Reporting application, we can allow the user to have multiple consolidation workbooks open at the same time and switch between them using the new Window menu, as shown in Figure 7-3.

Figure 7-3

Figure 7-3 The PETRAS Reporting menu bar with the new Window menu

Table 7-2 summarizes the changes made to the PETRAS time sheet application for this chapter. Rather than repeat much of the previous few pages, we suggest you review the PetrasReporting.xla workbook to see exactly how the multiple-document interface has been implemented.

Table 7-2. Changes to PETRAS Reporting Application for Chapter 7





Adds an application-level event handling class to the application to manage multiple consolidation workbooks.



Adds code to create the Window menu.


Adds procedures to add, remove, and place a tick mark against an item in the Window menu.



New procedure to handle selecting an item within the Window menu. All Window menu items call this routine.

  • + Share This
  • 🔖 Save To Your Account