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. You can also create a new collection for the object, such as the Employees collection. The class module is a plan for the objects you want to create. From it you can create instances of your object. For example, Mary, Jack, and Anne could be instances of an Employee object, all belonging to the Employees collection.

You might not be aware of it, but you have been using some class modules already. The modules behind worksheets, charts, workbooks, and UserForms are class modules. However, they are special types of class modules that behave a little differently from those you create yourself. They are designed specifically to support the object with which they are associated, they give you access to the event procedures for that object, and they cannot be deleted without deleting the associated object.

Was this article helpful?

0 0
The Accidental Blogging Millionaires

The Accidental Blogging Millionaires

Get Inspired By The Most Popular Bloggers Online! If You Want To Skyrocket Your Success With Business And Improve Your Overall Life You Need To Have A Look At The Accidental Blogging Millionaires! Business can be a fight, particularly when you’re trying to establish one online and like all fights, to succeed you must find the winning techniques and apply them.

Get My Free Ebook

Post a comment