Chapter 16. Class Modules

Class modules are used in VBA to create your own customized objects. Most VBA users will never have to create their own objects because Excel already provides all of the objects they need. However, there are occasions when class modules can be very useful. You can use them to:

  • Respond to application events; you can write code that is executed whenever any open workbook is saved or printed, for example

  • Respond to embedded chart events

  • Set up a single event procedure that can be used by a number of ActiveX controls, such as text boxes in a UserForm

  • Encapsulate Windows API code so it is easy to use

  • Encapsulate standard VBA procedures in a form that is easy to transport into other workbooks

In this chapter, you create some simple (if not terribly useful) objects, to get the idea of how class modules work. Then you apply the principles to some more useful examples. You are already familiar with Excel's built-in objects, such as the Worksheet object, and you know that objects often belong to collections such as the Worksheets collection. You also know that objects have properties and methods, such as the Name property and the Copy method of the Worksheet object.

Using a class module, you can create your own "blueprint" for a new object, such as an Employee object. You can define properties and methods for the object, such as a Rate property that records the employee's current rate of pay, and a Training method that consumes resources and increases the employee's skills. ...

Get Excel® 2007 VBA Programmer's Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.