Excel 2007 Power Programming with VBA (Mr. Spreadsheets Bookshelf)
A class module is a special type of VBA module that you can insert into a VBA project. Basically, a class module enables the programmer (you) to create a new object class. As you should know by now, programming Excel really boils down to manipulating objects. A class module allows you to create new objects, along with corresponding properties, methods , and events.
CROSS-REFERENCE | Examples in previous chapters in this book use class modules. See Chapters 15, 18, 19, and 22. |
At this point, you might be asking, "Do I really need to create new objects?" The answer is no. You don't need to, but you might want to after you understand some of the benefits of doing so. In many cases, a class module simply serves as a substitute for functions or procedures, but it could be a more convenient and manageable alternative. In other cases, however, you'll find that a class module is the only way to accomplish a particular task.
Following is a list of some typical uses for class modules:
-
To handle events associated with embedded charts . (See Chapter 18 for an example.)
-
To monitor application-level events, such as activating any worksheet. (See Chapters 19 and 22 for examples.)
-
To encapsulate a Windows Application Programming Interface (API) function to make it easier to use in your code. For example, you can create a class that makes it easy to detect or set the state of the Num Lock or Caps Lock key. Or you can create a class that simplifies access to the Windows Registry.
-
To enable multiple objects in a UserForm to execute a single procedure. Normally, each object has its own event handler. The example in Chapter 15 demonstrates how to use a class module so that multiple CommandButtons have a single Click event handler procedure.
-
To create reusable components that can be imported into other projects. After you create a general-purpose class module, you can import it into other projects to reduce your development time.