Creating Custom Objects

There are two module commands available in the Visual Basic Editor's Insert menu: Module and Class Module. So far you've used a standard module to create Sub and Function procedures. You'll use the class module for the first time now to create a custom object and define its properties and methods.

Creating a new, non-standard VBA object involves inserting a class module into your project and adding code to that module. However, before you do so you need a basic understanding of what a class is.

If you refer back to the terminology section earlier in this chapter, you will find out that the class is a sort of object template. A frequently used analogy is comparing an object class to a cookie cutter. Just like a cookie cutter defines what a particular cookie will look like, the definition of the class determines how a particular object should look and how it should behave. Before you can actually use an object class, you must first create a new instance of that class. Object instances are the cookies. Each object instance has the characteristics

Part I

(properties and methods) defined by its class. Just as you can cut out many cookies using the same cookie cutter, you can create multiple instances of a class. You can change the properties of each instance of a class independently of any other instance of the same class.

A class module lets you define your own custom classes, complete with custom properties and methods. A property is an attribute of an object that defines one of its characteristics, such as shape, position, color, title, etc. A method is an action that the object can perform. You can create the properties for your custom objects by writing property procedures in a class module. The object methods are also created in a class module by writing the subprocedures or function procedures.

After building your object in the class module, you can use it in the same way you use other built-in objects. You can also export the object class outside the VBA project to other VBA-capable applications.

0 0

Post a comment