44
There is a way to get around this. You can indirectly access a UserForm in the referenced workbook if that
workbook has a function that returns a reference to the UserForm. There is an example of this type of func-
tion in the top-right corner of Figure 16-7. PassUserForm, in ClassUserFormControls.xlsm, is a func-
tion that assigns a new instance of frmFruitPricesto its return value. In ClassReferences.xlsm, mfrm
is declared as a generic Objecttype. ShowUserformassigns the return value of PassUserFormto mfrm.
mfrmcan then be used to show the UserForm and access its control values, as long as the UserForm is hid-
den, not unloaded.
Summary
Class modules are used to create blueprints for new objects, such as the Employeeobject presented in
this chapter:
❑
Functionand Subprocedures are used in the class module to create methods for the object.
❑
Publicvariables declare the properties for the object.
❑
However, if you need to take programmatic control when a property is assigned a value, you
can define the property using a PropertyLetprocedure.
❑
In addition, PropertyGetprocedures allow you to control access to property values.
To use the code in your class module, you create one or more instances of your object. For example, you
can create Maryand Jackas instances of an Employeeobject. You can further customize your objects by
creating your own collection, where you add all the instances of your object.
Class modules are not used to create objects to the same extent in Excel VBAas they are used in a stan-
dalone programming language such as Visual Basic. This is because Excel already contains the objects
that most Excel programmers want to use. However, Excel programmers can use class modules to:
❑
Trap application-level events, such as the WorkbookBeforePrintevent that allows you to con-
trol the printing of all open workbooks
❑
Trap events in embedded charts
❑
Write a single event procedure that can be used by many instances of a particular object, such as
a TextBoxcontrol on a UserForm
❑
Encapsulate difficult code and make it easier to use
❑
Encapsulate code so you can share the code among different projects and users
See Chapter 27 for examples of encapsulation of API code.
When you create a reference to another workbook, you should make sure that the
VBAProject in the referenced workbook has a unique name. By default, it will be
named VBAProject. Click Tools➪VBAProject Properties and enter a new project
name.
371
Chapter 16: Class Modules