Chapter 28: Object-Oriented Programming with VBA ................................................................
971
You can write custom objects to adapt to changing environments and user requirements. Most
often, you can exploit an object’s programmable nature by changing its properties and invoking its
methods. But you can engineer a custom object in such a way that the object automatically adapts
to differing conditions by running different internal routines.
You can create most object types multiple times in an application. Each time you create the object,
Access assigns it a unique name to distinguish it from other instances of the object. In other words,
a single Access program can host more than one instance of the object, with each object operating
independently of the others (possibly even cooperating with the other objects) and maintaining its
own set of properties and other data.
For example, say the Northwind Traders database (included with Microsoft Access) contains a
Product object. The class module supporting the Product object defines the Name, Supplier,
UnitPrice, and other properties of the product. There are any number of Product objects in
the Northwind Traders database, each with its own name, price, and supplier.
To carry the analogy further, another class module might define a ProductInventory collection
object that contains a number of Product objects. The ProductInventory class would feature
a Count property that tells you how many Product objects are in the collection. The Product
Inventory class module might contain a Sell method that deducts a certain Product item
from the ProductInventory.
Using objects in applications
Every time you’ve written code setting a label’s Caption property or returning the contents of a
text box’s Value, you’ve worked with objects. Although a label or text-box control is a simple type
of object, the principles behind these objects are the same as using more complex and intelligent
objects that you create yourself.
The following Access VBA code shows a series of statements that are typical of how you’d use
objects in Access applications:
Dim MyObject As ObjectClass
Set MyObject = New ObjectClass
‘Setting a property of the object:
MyObject.SomeProperty = SomeValue
‘Invoking a method of the object:
MyObject.SomeMethod
Some of this code might seem a little strange, especially the statement where MyObject is
assigned to a New ObjectClass. As you’ll see later in this chapter, all this statement does is cre-
ate a new object named MyObject that’s based on the ObjectClass class.
In this code, the name of the object is ObjectName and its object class (described in the next sec-
tion) is ObjectClass. You declare the object in the Dim statement and the New keyword instanti-
ates (creates) it. SomeProperty is a property of the object, and SomeMethod is a method of the
object.