Creating Custom Objects

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 beginning of this chapter, you will find out that a class is a sort of object template. A frequently used analogy is comparing an object class to a cookie cutter. Just as a cookie cutter defines what a particular cookie will look like, the definition of the class determines how a particular object should look and 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 (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. Recall that a property is an attribute of an object that defines one of its characteristics, such as shape, position, color, title, and so on. 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 Sub 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