VBA course · Lesson 29 of 33
Class modules: build your own objects in VBA
Create your own objects with class modules: private fields, Property Get/Let/Set, methods, Class_Initialize, collections of objects and WithEvents.
Throughout this course you have used objects that Excel gives you: a Range has a Value property and a ClearContents method, a Worksheet has a Name and a Delete method. A class module lets you design objects of your own in exactly the same style. You could create an Invoice object with properties such as Customer and NetAmount, and methods such as AddLine and Total. The rest of your code then talks about invoices instead of about "column 7 of row 12".
Classes are the most abstract topic in this course. You can write useful macros for years without them, so do not worry if they feel unusual at first. This lesson shows what they are, how to write one step by step, and, just as important, when they are worth the extra effort.
Class, object, instance
A class is a blueprint. It describes what data an object holds and what it can do, but it is not an object itself. An object (or instance) is one concrete thing built from that blueprint. One clsEmployee class can produce a hundred employee objects, each with its own name and salary. In Excel terms: Worksheet is the class, and the sheet called "January" is one instance.
Creating a class module
- In the VBA editor choose Insert > Class Module.
- In the Properties window (F4) change its (Name) from
Class1to something meaningful, for exampleclsEmployee. The name of the class module is the name of the new type. - Type
Option Explicitat the top, as in every module (VBA best practices: clean code, sharing and security).
The prefix cls is a common convention that makes class modules easy to spot in the Project Explorer. Some teams write just Employee; choose one style and stick to it.
A first class: clsEmployee
The simplest class just has public variables. Put this in a class module named clsEmployee:
Option Explicit
Public FullName As String
Public Department As String
Public AnnualSalary As CurrencyAnd this in a normal module:
Option Explicit
Sub TryEmployee()
Dim emp As clsEmployee
Set emp = New clsEmployee ' create an instance
emp.FullName = "Ana Silva"
emp.Department = "Finance"
emp.AnnualSalary = 48000
Debug.Print emp.FullName & " works in " & emp.Department
End SubTwo lines matter here. Dim emp As clsEmployee declares a variable that can point to an employee, and Set emp = New clsEmployee actually creates one. As with any object, you need Set to assign it. As soon as you type emp. the editor offers FullName, Department and AnnualSalary in the IntelliSense list: your class behaves like a built-in object.
Dim emp As New clsEmployee in one line. It works, but the object is created invisibly the first time you use the variable, and it comes back to life even after Set emp = Nothing. The two-line form is clearer and avoids surprises.Private fields and properties
Public fields are easy, but anybody can put anything in them: a negative salary, an empty name. The real strength of classes is encapsulation: keep the data private and control access through properties.
Property Getruns when someone reads the property.Property Letruns when someone assigns a normal value to it.Property Setruns when someone assigns an object to it (withSet).
Option Explicit
' Private fields: only code inside this class can see them
Private mFullName As String
Private mDepartment As String
Private mSalary As Currency
Private mStartDate As Date
Private Sub Class_Initialize()
' Runs automatically when New clsEmployee is executed
mDepartment = "Unassigned"
mStartDate = Date
End Sub
Public Property Get FullName() As String
FullName = mFullName
End Property
Public Property Let FullName(ByVal value As String)
value = Trim$(value)
If value = "" Then Err.Raise vbObjectError + 1, "clsEmployee", "Name cannot be empty."
mFullName = value
End Property
Public Property Get Department() As String
Department = mDepartment
End Property
Public Property Let Department(ByVal value As String)
mDepartment = value
End Property
Public Property Get AnnualSalary() As Currency
AnnualSalary = mSalary
End Property
Public Property Let AnnualSalary(ByVal value As Currency)
If value < 0 Then Err.Raise vbObjectError + 2, "clsEmployee", "Salary cannot be negative."
mSalary = value
End Property
Public Property Get StartDate() As Date
StartDate = mStartDate
End Property
Public Property Let StartDate(ByVal value As Date)
mStartDate = value
End Property
' Read-only calculated property: there is no Property Let for it
Public Property Get MonthlySalary() As Currency
MonthlySalary = Round(mSalary / 12, 2)
End Property
Public Property Get YearsOfService() As Long
YearsOfService = DateDiff("yyyy", mStartDate, Date)
' Not yet reached the anniversary this year: subtract one
If DateSerial(Year(Date), Month(mStartDate), Day(mStartDate)) > Date Then
YearsOfService = YearsOfService - 1
End If
End Property
' A method: a Sub or Function inside the class
Public Sub GiveRaise(ByVal percent As Double)
mSalary = Round(mSalary * (1 + percent / 100), 2)
End SubThe m prefix ("member") marks private fields, so mSalary and the property AnnualSalary never clash. Note what you gained:
- Validation in one place. Every piece of code that sets
AnnualSalarygoes through the same check. A negative salary raises a clear error instead of quietly entering a report. - Calculated, read-only properties.
MonthlySalaryandYearsOfServicehave only aProperty Get, so code can read them but never set them. They are always consistent with the salary and start date. - Defaults.
Class_Initializeruns once when the object is created. Its partnerClass_Terminateruns when the last reference to the object disappears, useful for clean-up. - Methods.
GiveRaisechanges the object's own data. The calling code does not need to know how the rounding works.
Err.Raise vbObjectError + n is the standard way for a class to report an error to the code that uses it; the caller handles it with the usual On Error techniques from Error handling and debugging in VBA.
A collection of objects: loading staff from a sheet
Objects become really useful in groups. This module reads a staff table, creates one clsEmployee per row, stores them in a Collection (Collections and dictionaries in VBA) and then works with the objects.
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Name | Department | Salary | Start date |
| 2 | Ana Silva | Finance | 48000 | 2019-04-01 |
| 3 | Ben Okafor | Sales | 39500 | 2022-09-15 |
| 4 | Chen Wei | IT | 56000 | 2016-01-11 |
| 5 | Dana Novak | Sales | 42000 | 2021-06-07 |
The Staff sheet
Option Explicit
Function LoadStaff(ByVal ws As Worksheet) As Collection
Dim result As New Collection
Dim emp As clsEmployee
Dim r As Long
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
For r = 2 To lastRow
Set emp = New clsEmployee ' a NEW object for every row
emp.FullName = ws.Cells(r, "A").Value
emp.Department = ws.Cells(r, "B").Value
emp.AnnualSalary = ws.Cells(r, "C").Value
emp.StartDate = ws.Cells(r, "D").Value
result.Add emp, emp.FullName ' key = name
Next r
Set LoadStaff = result
End Function
Sub StaffReport()
Dim staff As Collection
Dim emp As clsEmployee
Dim salesTotal As Currency
Set staff = LoadStaff(ThisWorkbook.Worksheets("Staff"))
For Each emp In staff
If emp.Department = "Sales" Then
emp.GiveRaise 3
salesTotal = salesTotal + emp.AnnualSalary
End If
Debug.Print emp.FullName, emp.MonthlySalary, emp.YearsOfService & " yrs"
Next emp
Debug.Print "Sales payroll after a 3% raise: "; salesTotal
Debug.Print "Chen's monthly salary: "; staff("Chen Wei").MonthlySalary
End SubRead StaffReport aloud and it almost sounds like English: "for each employee in staff, if the department is Sales, give a 3% raise". That readability is the main payoff of classes. The function returns an object, so it uses Set LoadStaff = result (Functions and Subs: parameters, ByVal, ByRef and return values).
Set emp = New clsEmployee once, before the loop. Then every row overwrites the same object and the collection ends up holding four references to one employee, all showing the last row's data. Create a new instance inside the loop.Objects inside objects: Property Set
Properties can hold other objects. An invoice has lines; a line could be its own class. Here is a compact invoice class that uses a Collection of lines and a Property Set for the customer's worksheet range.
Option Explicit
Public Description As String
Public Quantity As Double
Public UnitPrice As Currency
Public Property Get LineTotal() As Currency
LineTotal = Quantity * UnitPrice
End PropertyOption Explicit
Private mNumber As String
Private mCustomer As String
Private mVatRate As Double
Private mLines As Collection
Private mOutputCell As Range
Private Sub Class_Initialize()
Set mLines = New Collection
mVatRate = 0.2 ' default 20% VAT
End Sub
Public Property Get Number() As String
Number = mNumber
End Property
Public Property Let Number(ByVal value As String)
mNumber = value
End Property
Public Property Get Customer() As String
Customer = mCustomer
End Property
Public Property Let Customer(ByVal value As String)
mCustomer = value
End Property
Public Property Let VatRate(ByVal value As Double)
mVatRate = value
End Property
' Property Set because a Range is an object
Public Property Set OutputCell(ByVal target As Range)
Set mOutputCell = target
End Property
Public Sub AddLine(ByVal desc As String, ByVal qty As Double, ByVal price As Currency)
Dim ln As clsInvoiceLine
Set ln = New clsInvoiceLine
ln.Description = desc
ln.Quantity = qty
ln.UnitPrice = price
mLines.Add ln
End Sub
Public Function NetTotal() As Currency
Dim ln As clsInvoiceLine
For Each ln In mLines
NetTotal = NetTotal + ln.LineTotal
Next ln
End Function
Public Function GrossTotal() As Currency
GrossTotal = Round(NetTotal * (1 + mVatRate), 2)
End Function
Public Sub WriteSummary()
If mOutputCell Is Nothing Then Err.Raise vbObjectError + 10, "clsInvoice", "Set OutputCell first."
mOutputCell.Resize(1, 4).Value = Array(mNumber, mCustomer, NetTotal, GrossTotal)
End SubOption Explicit
Sub DemoInvoice()
Dim inv As clsInvoice
Set inv = New clsInvoice
inv.Number = "INV-2026-0042"
inv.Customer = "Brightway"
inv.AddLine "Desk lamp", 4, 32.5
inv.AddLine "Office chair", 2, 149
Set inv.OutputCell = ThisWorkbook.Worksheets("Summary").Range("A2")
inv.WriteSummary
Debug.Print inv.NetTotal, inv.GrossTotal ' 428 513.6
End SubThe calling code never touches the Collection of lines; it only calls AddLine. If you later decide to store lines in an array or a dictionary, only the class changes. That freedom to change the inside without breaking the outside is what encapsulation buys you.
WithEvents: catching another object's events
A class can also listen to events of an Excel object. Declaring a variable WithEvents inside a class makes its events available in the class's drop-down lists, just like the events of a worksheet module (Events: macros that run by themselves). The classic use is catching events of every workbook through the Application object.
Option Explicit
Public WithEvents App As Application
Private Sub App_WorkbookBeforeSave(ByVal Wb As Workbook, ByVal SaveAsUI As Boolean, Cancel As Boolean)
' Runs before ANY workbook is saved while this object exists
Application.StatusBar = "Saving " & Wb.Name & " at " & Format(Now, "hh:mm")
End SubOption Explicit
Private appEvents As clsAppEvents ' module-level, so it stays alive
Sub StartListening()
Set appEvents = New clsAppEvents
Set appEvents.App = Application
End Sub
Sub StopListening()
Set appEvents = Nothing
Application.StatusBar = False
End SubThe object has to stay alive, so the variable lives at module level. If you reset the VBA project (the square Reset button) or an unhandled error stops the code, the variable is cleared and the listener quietly stops. Run StartListening from Workbook_Open to switch it on automatically. The same WithEvents idea lets one class handle the clicks of many text boxes on a UserForm (UserForms: build a data-entry form in VBA).
When are classes worth it?
Classes add files and ceremony. They pay off when:
- the same kind of "thing" (invoice, employee, order) appears in several macros and has rules that should live in one place;
- you have several values that belong together and you are tired of parallel arrays;
- you want to catch events of many controls or of the Application object;
- the project is large and several people work on it.
For a 30-line macro that formats one report, a class is overkill. Start with plain procedures, and introduce a class when you notice the same group of variables and checks repeated in many places.
Common mistakes
- Forgetting
Setwhen creating an instance or assigning an object property. - Creating the object once outside a loop, so all items in a collection are the same object.
- Using
Property Letfor an object property: objects needProperty Set. - A
Property Getand itsProperty Letwith different data types: the editor refuses to compile them. - Expecting
Class_Initializeto accept arguments. It cannot; the common workaround is a publicInitmethod that you call right afterNew. - Classes are code-only: you cannot use them directly in a worksheet formula.
Check yourself
1. What is the relationship between a class and an object?
One clsEmployee class can produce many employee objects, each with its own data.
2. Which procedure runs when code reads a property?
Get reads, Let assigns a value, Set assigns an object.
3. How do you make a calculated property read-only?
Without a Let or Set procedure, code outside the class cannot assign the property.
4. After a loop that adds four employees to a collection, all four show the last row's data. What is the likely cause?
A new instance must be created inside the loop; otherwise each Add stores another reference to the same object.
5. Why is the WithEvents variable for the Application declared at module level?
A local variable disappears when its procedure ends, and with it the event listener.