Class modules are a special type of module that allow you to create your own customised objects.
You can define the methods and properties for them and even write event handlers.
These are similar to form modules, except they have no visible user interface.
A class module can contain declarations, properties, methods and events
Properties, Methods and Events
An object is anything that you want it to be and is defined entirely by its properties, methods, and events.
Properties - These are the "Adjectives" which describe an object. Also known as property procedures.
Methods - These are the "Verbs" of objects. These are subroutines and functions.
Events - These are how an object tells the rest of the world that something happened.
Once you've defined the Class, you never have to worry about the individual properties and methods you can just use them.
Lets create a simple class based on an employee to illustrate how to use classes.
First you would insert a class module called "Employee".
This Employee class will define a single, generic, employee.
To work with one particular employee, you just call the properties and methods for that employee.
Public Sub TestingEmployeeClass()
Dim objEmployee As CEmployee
Set objEmployee = New CEmployee
objEmployee.Name = "Russell"
objEmployee.Department = "Research"
objEmployee.HourlyRate = 12.75
objEmployee.HoursPerWeek = 35
Call MsgBox(objEmployee.Name & " earns £" & objEmployee.WeeklyPay & " a week")
Set objEmployee = Nothing
Reasons for not using a Class Module
1) No intellisense - if passed or declared as Objects or Variants (commonly done/lazy)
2) Harder/impossible to make changes at run-time. You always have to reset the project
3) Must be slower - prove this with an example
4) Must use more resources - prove this with an example
5) The Watch window only displays 256 items in a collection. Classes are always used in conjunction with collections
6) The Watch window displays duplicates, properties and private variables - SS
7) If properties and private variables have the same name then infinite loops can occur, resulting in "Out of Stack" run-time errors.
Reasons for using a Class Module
There are a few occasions when a class module is necessary:
1) Responding to events (application or chart)
2) Creating a single event for multiple controls. Using a Controls Collection
3) Encapsulating your VBA procedures and functions (or even Windows API calls) so they are easier to use
Class Modules let you create your own objects and allow you to define the corresponding properties and methods.
Remember that userforms are a type of class module although they behave differently to the ones you can create.
The class module name is the name of the class you are creating.