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.

Advanced 22 min read

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

  1. In the VBA editor choose Insert > Class Module.
  2. In the Properties window (F4) change its (Name) from Class1 to something meaningful, for example clsEmployee. The name of the class module is the name of the new type.
  3. Type Option Explicit at 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:

VBA
Option Explicit

Public FullName As String
Public Department As String
Public AnnualSalary As Currency
Class module clsEmployee, version 1: public fields

And this in a normal module:

VBA
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 Sub
Using the class from a standard module

Two 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.

Note. You may see 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 Get runs when someone reads the property.
  • Property Let runs when someone assigns a normal value to it.
  • Property Set runs when someone assigns an object to it (with Set).
VBA
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 Sub
Class module clsEmployee, version 2: private fields with validation

The 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 AnnualSalary goes through the same check. A negative salary raises a clear error instead of quietly entering a report.
  • Calculated, read-only properties. MonthlySalary and YearsOfService have only a Property Get, so code can read them but never set them. They are always consistent with the salary and start date.
  • Defaults. Class_Initialize runs once when the object is created. Its partner Class_Terminate runs when the last reference to the object disappears, useful for clean-up.
  • Methods. GiveRaise changes 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.

ABCD
1NameDepartmentSalaryStart date
2Ana SilvaFinance480002019-04-01
3Ben OkaforSales395002022-09-15
4Chen WeiIT560002016-01-11
5Dana NovakSales420002021-06-07

The Staff sheet

VBA
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 Sub
Standard module: build employee objects and use them

Read 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).

Watch out. The most common class bug: writing 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.

VBA
Option Explicit

Public Description As String
Public Quantity As Double
Public UnitPrice As Currency

Public Property Get LineTotal() As Currency
    LineTotal = Quantity * UnitPrice
End Property
Class module clsInvoiceLine
VBA
Option 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 Sub
Class module clsInvoice
VBA
Option 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 Sub
Standard module: use the invoice class

The 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.

VBA
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 Sub
Class module clsAppEvents
VBA
Option 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 Sub
Standard module: switch the listener on and off

The 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 Set when 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 Let for an object property: objects need Property Set.
  • A Property Get and its Property Let with different data types: the editor refuses to compile them.
  • Expecting Class_Initialize to accept arguments. It cannot; the common workaround is a public Init method that you call right after New.
  • 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?

2. Which procedure runs when code reads a property?

3. How do you make a calculated property read-only?

4. After a loop that adds four employees to a collection, all four show the last row's data. What is the likely cause?

5. Why is the WithEvents variable for the Application declared at module level?