Tabellab

Why Classes: One Object Instead of Parallel Arrays

Lesson 1 of 8Reading

One key, twelve employees, two bad rows caught

A few minutes from now you will press F5 and a new sheet appears: 12 employees under a blue header, 6 juniors in green with a 3% rise, a payroll of 767,535.50, and two broken input rows (a negative salary, a missing name) refused with a clear reason instead of slipping quietly into the total. The part that makes this possible is a class module: your own object type, CEmployee, that holds an employee's data and guards it. All companies, names and numbers are fictional.

You already use objects all day

Worksheet, Range, Collection: each is an object. It holds data (a Range has a .Value) and knows how to do things (.Copy). A class module lets you define your own. If your macro deals with employees, you can have an Employee object with a .Salary and an .ApplyRise method instead of four parallel arrays like these:

' Before: four arrays and an unwritten promise that they stay in step
Sub OldPayRise()
    Dim names(1 To 100) As String
    Dim teams(1 To 100) As String
    Dim salaries(1 To 100) As Double
    Dim raised(1 To 100) As Boolean
    Dim i As Long

    For i = 1 To 100
        If salaries(i) < 60000 Then
            salaries(i) = salaries(i) * 1.03
            raised(i) = True
        End If
    Next i
End Sub

Four arrays indexed by the same i, with nothing but discipline keeping them aligned. Sort one and everything is silently wrong. Add a field and you touch every procedure. Pass an employee onward and you pass four arguments in an order nobody remembers. And a negative salary is accepted without a word.

Run it in six steps

  1. Press Alt+F11 for the VBA editor, then Ctrl+R for the Project Explorer (on a Mac: View โ†’ Project Explorer).
  2. Right-click VBAProject (YourFile.xlsm) in that tree, then Insert โ†’ Class Module. It appears under a folder called Class Modules; if yours landed under Modules, you picked the wrong entry.
  3. Press F4 for the Properties window (or View โ†’ Properties Window) and set (Name) to CEmployee. This is the only place a class is named: typing the name in the code does nothing.
  4. Paste Part 1 into that class module.
  5. Choose Insert โ†’ Module for an ordinary module and paste Part 2 there.
  6. Click inside Sub StaffDemo, press F5 and switch back to Excel. Save as .xlsm, or both modules are gone when you reopen the file.
The macro only adds a new sheet and writes into it. Nothing on your existing sheets is read or changed, and each run makes a fresh tab, so you can run it as often as you like.

Part 1: the class module CEmployee

Option Explicit

' ---- CEmployee : goes in a CLASS module named CEmployee ----

Private Const JUNIOR_LIMIT As Double = 60000

Private mFullName As String
Private mTeam As String
Private mSalary As Double

Public Property Get FullName() As String
    FullName = mFullName
End Property

Public Property Let FullName(ByVal newValue As String)
    newValue = Trim$(newValue)
    If Len(newValue) = 0 Then
        Err.Raise vbObjectError + 513, "CEmployee", "A name cannot be empty."
    End If
    mFullName = newValue
End Property

Public Property Get Team() As String
    Team = mTeam
End Property

Public Property Let Team(ByVal newValue As String)
    mTeam = Trim$(newValue)
End Property

Public Property Get Salary() As Double
    Salary = mSalary
End Property

Public Property Let Salary(ByVal newValue As Double)
    If newValue < 0 Then
        Err.Raise vbObjectError + 514, "CEmployee", _
                  "A salary cannot be negative: " & newValue
    End If
    mSalary = newValue
End Property

' read-only and calculated: nothing to keep in sync
Public Property Get IsJunior() As Boolean
    IsJunior = (mSalary < JUNIOR_LIMIT)
End Property

' a method: the object changes its own salary
Public Sub ApplyRise(ByVal fraction As Double)
    mSalary = mSalary * (1 + fraction)
End Sub

Part 2: the standard module

Option Explicit

' ---- goes in a STANDARD module (Insert - Module) ----

Sub StaffDemo()
    Const RISE As Double = 0.03

    Dim rowsData As Variant
    Dim staff As Collection
    Dim refused As Collection
    Dim emp As CEmployee
    Dim ws As Worksheet
    Dim reason As String
    Dim i As Long
    Dim r As Long
    Dim raised As Long
    Dim payroll As Double

    ' --- 14 fictional input rows, two of them broken on purpose ---
    rowsData = Array( _
        "Anna Keller|Sales|58000", "Marco Rossi|Finance|72000", _
        "Lea Studer|Support|49500", "Tom Brunner|Sales|61000", _
        "Sofia Vogt|Support|55250", "Jonas Meier|IT|-4200", _
        "Nina Frei|Finance|83500", "David Huber|IT|67800", _
        "|Sales|51000", "Elena Graf|Marketing|57400", _
        "Lukas Baumann|IT|59900", "Mia Schmid|Marketing|64300", _
        "Paul Wyss|Support|52800", "Clara Roth|Finance|76100")

    ' 1 - one object per row; the class itself refuses bad data
    Set staff = New Collection
    Set refused = New Collection
    For i = LBound(rowsData) To UBound(rowsData)
        reason = AddEmployee(staff, rowsData(i))
        If Len(reason) > 0 Then refused.Add reason
    Next i

    ' 2 - a new sheet with a header
    Set ws = ThisWorkbook.Worksheets.Add
    ws.Name = "Staff " & Format(Now, "hh-mm-ss")
    ws.Range("A1:D1").Value = Array("Employee", "Team", "Salary", "Status")
    With ws.Range("A1:D1")
        .Font.Bold = True
        .Font.Color = vbWhite
        .Interior.Color = RGB(30, 64, 175)
    End With

    ' 3 - the business rule, written the way you would say it
    r = 2
    For Each emp In staff
        If emp.IsJunior Then
            emp.ApplyRise RISE
            raised = raised + 1
            ws.Cells(r, 4).Value = Format(RISE, "0%") & " rise"
            ws.Range(ws.Cells(r, 1), ws.Cells(r, 4)).Interior.Color = RGB(220, 252, 231)
        End If
        ws.Cells(r, 1).Value = emp.FullName
        ws.Cells(r, 2).Value = emp.Team
        ws.Cells(r, 3).Value = emp.Salary
        payroll = payroll + emp.Salary
        r = r + 1
    Next emp

    ' 4 - payroll under the table, then the refused rows
    ws.Cells(r + 1, 2).Value = "Payroll"
    ws.Cells(r + 1, 3).Value = payroll
    ws.Range(ws.Cells(r + 1, 2), ws.Cells(r + 1, 3)).Font.Bold = True
    ws.Range("C2:C" & r + 1).NumberFormat = "#,##0.00"
    ws.Columns("A:D").AutoFit

    ws.Cells(r + 3, 1).Value = "Refused rows"
    ws.Cells(r + 3, 1).Font.Bold = True
    For i = 1 To refused.Count
        ws.Cells(r + 3 + i, 1).Value = refused(i)
        ws.Cells(r + 3 + i, 1).Font.Color = RGB(185, 28, 28)
    Next i

    MsgBox UBound(rowsData) + 1 & " rows read: " & staff.Count & " employees, " & _
           refused.Count & " refused." & vbNewLine & _
           raised & " juniors got a " & Format(RISE, "0%") & " rise." & vbNewLine & _
           "Payroll: " & Format(payroll, "#,##0.00"), vbInformation, "Staff demo"
End Sub

' returns "" when the row became an employee, otherwise the reason it was refused
Private Function AddEmployee(ByVal staff As Collection, ByVal rowText As String) As String
    Dim parts As Variant
    Dim emp As CEmployee

    On Error GoTo BadRow
    parts = Split(rowText, "|")

    Set emp = New CEmployee          ' a fresh object for every row
    emp.FullName = parts(0)
    emp.Team = parts(1)
    emp.Salary = Val(parts(2))

    staff.Add emp
    Exit Function

BadRow:
    AddEmployee = Err.Description & "  (" & rowText & ")"
End Function

What you see on the new sheet

  • A tab called Staff plus the current time, e.g. Staff 14-03-22, with Employee, Team, Salary, Status in bold white on blue in A1:D1.
  • A2:D13: 12 employees in input order. Jonas Meier and the row without a name are not there.
  • 6 green rows marked 3% rise: Anna Keller 58,000 โ†’ 59,740.00, Lea Studer 49,500 โ†’ 50,985.00, Sofia Vogt 55,250 โ†’ 56,907.50, Elena Graf 57,400 โ†’ 59,122.00, Lukas Baumann 59,900 โ†’ 61,697.00 and Paul Wyss 52,800 โ†’ 54,384.00.
  • B15:C15: Payroll 767,535.50, after the rises.
  • A17:A19, in red: Refused rows, then A salary cannot be negative: -4200 (Jonas Meier|IT|-4200) and A name cannot be empty. (|Sales|51000).
  • A message box: 14 rows read: 12 employees, 2 refused. 6 juniors got a 3% rise. Payroll: 767,535.50.

Reading it line by line

  1. The Private mโ€ฆ variables are the object's memory. Code outside the class cannot touch them; it has to go through the properties.
  2. Property Get reads, Property Let writes. emp.Salary = 58000 calls the Let; x = emp.Salary calls the Get. From outside both look like a plain variable.
  3. Err.Raise inside the Let is the payoff: the check lives in one place, and every caller gets it, including code someone writes next year. A negative salary is stopped at the door.
  4. IsJunior is a Get with no Let: read-only, calculated on demand from the current salary. That is why Lukas Baumann (59,900) gets the rise, yet would no longer count as junior straight afterwards (61,697).
  5. ApplyRise is a method: a Public Sub inside the class. The object changes its own salary; the calling code just says what should happen.
  6. AddEmployee makes a fresh object per row with Set emp = New CEmployee. When the class refuses a value, On Error GoTo BadRow catches it, the half-built object is never added, and the reason comes back as text.
  7. For Each emp In staff: the business rule now reads like the sentence you would say out loud, with no index arithmetic in sight.

Arrays or a class: the same job, side by side

  • Add a field (say, a start date): arrays need a new array and a change in every procedure that passes the data around. The class needs one Private variable and one Get/Let pair.
  • Sort or delete a row: arrays must be moved in step by hand, all four of them. With a class you move one object.
  • Pass one employee on: arrays mean four arguments plus an index. With a class it is one argument: PrintCard emp.
  • Reject bad data: with arrays, wherever someone remembers to check. With a class, once, in the Let, for every caller.
  • Change a rule: with arrays, hunt for every < 60000. With a class, one line: JUNIOR_LIMIT.

Try it: three one-minute changes

1. Change Const RISE As Double = 0.03 to 0.05 and run again: still 6 green rows, column D now says 5% rise and the payroll becomes 774,192.50. 2. Put RISE back to 0.03 and, in the class module, change JUNIOR_LIMIT to 55000: only Lea Studer and Paul Wyss turn green and the payroll drops to 760,619.00. The rule changed in one line, and the standard module was not touched. 3. Put the limit back to 60000 and repair Jonas Meier's row: -4200 becomes 64200. Now the message says 13 employees and 1 refused, and the payroll is 831,735.50 (he earns too much to count as junior).

Typical mistakes (everyone makes them once)

  • Class code in a standard module: the properties compile without complaint, but no type of that name exists, so New CEmployee stops with Compile error: User-defined type not defined. The class must sit under Class Modules in the Project Explorer.
  • The class is still called Class1: same error, same message. The name in the Properties window is the type name, and it must match the name after New letter for letter.
  • Forgetting Set: emp = New CEmployee fails with run-time error 91, Object variable or With block variable not set. Objects are assigned with Set emp = New CEmployee.
  • Saving as .xlsx: that format cannot store code, and both modules are gone on reopening. Use Excel Macro-Enabled Workbook (.xlsm).
If the editor stops inside Property Let Salary instead of reporting the refused row, look at Tools โ†’ Options โ†’ General โ†’ Error Trapping. With Break in Class Module selected, every error raised in a class halts there, even when the caller has a handler. Break on Unhandled Errors (the usual setting) passes it on to AddEmployee as intended.

The trap: one New, many rows

It looks tidy to create the object once, above the loop, and just refill it. But an object variable holds a reference (an arrow to the object), not a copy. staff.Add emp stores the arrow, so every entry ends up pointing at the same single object:

Dim staff As Collection
Dim emp As CEmployee
Dim i As Long

Set staff = New Collection
Set emp = New CEmployee            ' once, above the loop: the bug
For i = 1 To 3
    emp.FullName = "Person " & i
    staff.Add emp
Next i

Debug.Print staff.Count              ' 3
Debug.Print staff(1).FullName        ' Person 3  - not Person 1
Debug.Print staff(1) Is staff(3)     ' True: one object, three entries
No error, no warning: the Collection simply holds three copies of the last row. That is why Set emp = New CEmployee sits inside AddEmployee, which runs once per row. Rule of thumb: one New per thing you want to keep.

When not to bother

Classes are not free. A twenty-line formatting macro needs none, and wrapping it in one only makes it harder to read. A quick test: can you name the thing with one noun? Invoice, Employee, Order, Logger. If the honest answer is a verb, it is probably just a Sub. The signal that a class will pay off is repetition: the same group of variables written out again and again, or arrays kept in step by hand.

How the course goes on

Next, Creating Your First Class slows the insert-and-name routine right down, separates the blueprint from the instance, and explains why Dim โ€ฆ As New is best avoided. Properties: Get, Let and Set shows why a private field behind a public property beats a Public variable, how read-only and calculated properties work, and why an object-valued property needs Set. Methods: Giving the Object Something to Do covers Public, Private and Friend and when something should be a method rather than a property. After that come Class_Initialize and Class_Terminate, collections of objects, a worked invoice example, and splitting a big macro into modules.

Who this is for, and the problem classes solve

If you have written VBA for a while, you know the moment when a macro stops being fun. It started as fifty lines. Now it is eight hundred, it passes six arguments to every procedure, it keeps a handful of arrays that must stay in the same order, and nobody, including you, wants to change it. This lesson is for that person: an Excel user who already writes working macros and wants them to stay readable as they grow. The tool for that is the class module, the most underused feature in VBA.

A class module lets you define your own object type. Instead of a name in one array, a team in another and a salary in a third, you get one CEmployee object that holds all three, refuses nonsense like a negative salary, and knows how to give itself a pay rise. In the lab above you run exactly that: 14 fictional input rows go in, 12 employees come out on a new sheet, 6 juniors get a 3% rise, the payroll is 767,535.50, and two broken rows are refused with a clear reason instead of slipping into the total. This article explains why that design works, so that you can apply it to your own invoices, orders, projects or whatever nouns your macros deal with.

The core idea: data and rules in one place

You already use objects every day. A Range holds data (its .Value) and can do things (it can .Copy or .ClearContents). A Worksheet has a .Name and can .Activate. Excel's designers decided what a range is and what it can do. A class module lets you make the same decision for the things your own business deals with.

The alternative most macros use is parallel arrays: one array per field, all indexed by the same counter i. It works, but nothing in the language holds those arrays together. Sort one of them and every row is silently wrong. Add a field and you change every procedure that passes the data around. Hand one employee to another procedure and you pass four arguments in an order someone has to remember. And a negative salary goes straight into the total, because nothing is in charge of checking it.

Before: four parallel arraysAfter: one object per employeenames()Anna KellerMarco RossiLea Studerteams()SalesFinanceSupportsalaries()580007200049500raised()TrueFalseTrueLinked only by the index i (1, 2, 3 ...).Sort one array and every row is wrong.CEmployee: Anna KellerTeam Sales, Salary 58,000, IsJunior TrueCEmployee: Marco RossiTeam Finance, Salary 72,000, IsJunior FalseCEmployee: Lea StuderTeam Support, Salary 49,500, IsJunior TrueData and rules travel together.Sort, pass or delete one object, nothing drifts.Same three employees, two ways to hold them
The same three fictional employees held two ways. On the left the rows only line up because the code is careful. On the right each object carries its own data.

With a class, the four promises the arrays depend on become one rule enforced by the language: an employee is a single thing. The object's data lives in Private variables that no other module can touch. Other code reads and writes it through properties, and a property can check a value before accepting it. Behaviour lives in methods, which are simply Public Sub or Public Function procedures inside the class.

The class in the lab, reduced to its essentials

Here is the heart of CEmployee from the lab, with the name and team properties left out to keep it short. Everything that defines what an employee is, and what a valid salary is, sits in these few lines.

Option Explicit ' class module named CEmployee (extract) Private Const JUNIOR_LIMIT As Double = 60000 Private mSalary As Double Public Property Get Salary() As Double Salary = mSalary End Property Public Property Let Salary(ByVal newValue As Double) If newValue < 0 Then Err.Raise vbObjectError + 514, "CEmployee", _ "A salary cannot be negative: " & newValue End If mSalary = newValue End Property Public Property Get IsJunior() As Boolean IsJunior = (mSalary < JUNIOR_LIMIT) End Property Public Sub ApplyRise(ByVal fraction As Double) mSalary = mSalary * (1 + fraction) End Sub

  • Private mSalary is the field. Outside the class it does not exist, so the only way in is through the property.
  • Property Get Salary runs when code reads emp.Salary. Property Let Salary runs when code writes emp.Salary = 58000. From outside, both look like a plain variable.
  • Err.Raise in the Let is the payoff. The check is written once, and every caller, including code someone adds next year, goes through it.
  • IsJunior is a Get with no Let: a read-only, calculated property. It never needs updating, because it is worked out from the current salary each time it is read.
  • ApplyRise is a method. The calling code says what should happen, and the object changes its own salary.

Because the rules live in the class, the code that uses it reads almost like the business rule spoken out loud. This is the loop at the centre of the lab's standard module, without the formatting lines:

For Each emp In staff If emp.IsJunior Then emp.ApplyRise 0.03 payroll = payroll + emp.Salary Next emp

The worked example: 14 rows, 12 employees, 2 refusals

The lab feeds the class 14 fictional rows of text in the form Name|Team|Salary. Two are broken on purpose: Jonas Meier has a salary of -4,200 and one row has no name at all. The table shows what happens to every row. Salaries below the junior limit of 60,000 get the 3% rise, the rest are kept, and the two broken rows never become employees.

RowEmployeeTeamInput salaryWhat the class doesSalary on the sheet
1Anna KellerSales58,000junior, 3% rise59,740.00
2Marco RossiFinance72,000kept72,000.00
3Lea StuderSupport49,500junior, 3% rise50,985.00
4Tom BrunnerSales61,000kept61,000.00
5Sofia VogtSupport55,250junior, 3% rise56,907.50
6Jonas MeierIT-4,200refused: A salary cannot be negative-
7Nina FreiFinance83,500kept83,500.00
8David HuberIT67,800kept67,800.00
9(empty)Sales51,000refused: A name cannot be empty.-
10Elena GrafMarketing57,400junior, 3% rise59,122.00
11Lukas BaumannIT59,900junior, 3% rise61,697.00
12Mia SchmidMarketing64,300kept64,300.00
13Paul WyssSupport52,800junior, 3% rise54,384.00
14Clara RothFinance76,100kept76,100.00
Total12 kept, 2 refused757,5506 juniors raised767,535.50

Look at Lukas Baumann. At 59,900 he is a junior, so he gets the rise and ends at 61,697.00. If you read IsJunior again after the rise it returns False, because it is calculated from the current salary. That is correct behaviour, and it is the kind of detail that is easy to get wrong with a separate raised() array that has to be kept in step by hand.

The six juniors: salary before and after the 3% riseBeforeAfter ApplyRise 0.030k10k20k30k40k50k60k70kAnna Keller58,00059,740.00Lea Studer49,50050,985.00Sofia Vogt55,25056,907.50Elena Graf57,40059,122.00Lukas Baumann59,90061,697.00Paul Wyss52,80054,384.00JUNIOR_LIMIT 60,000
The six fictional juniors before (lavender) and after (mint) the 3% rise. Lukas Baumann crosses the 60,000 limit after his rise.

You can check the macro's arithmetic with ordinary worksheet formulas. Put the 12 accepted names in A2:A13, teams in B2:B13 and the input salaries in C2:C13, then add these formulas. They must agree with the numbers the macro writes, which is a good habit for any macro that produces money values.

CellFormulaResult
D2 (copy to D13)=IF(C2<60000,C2*1.03,C2)salary after the rule, e.g. 59,740.00 for Anna Keller
F1=COUNTIF(C2:C13,"<60000")6 juniors
F2=SUM(C2:C13)757,550 before rises
F3=SUM(D2:D13)767,535.50, the same payroll the macro writes
F4=SUMPRODUCT((C2:C13<60000)*C2:C13)*0.039,985.50, the cost of the rises

Where the 14 input rows go14 rowsName|Team|SalaryNew CEmployeeone per rowProperty Letname not emptysalary not < 0staff.Add12 employeesrefused.Add2 rows + reasonokErr.RaiseThe check lives in the class once, so every caller gets it.
The path of every input row. Each row gets its own new object, the property checks decide, and only valid objects reach the staff collection.

How to build it in Excel, step by step

  1. Save your workbook as Excel Macro-Enabled Workbook (*.xlsm) with F12. An .xlsx file cannot store code, and both modules would be gone when you reopen it.
  2. Press Alt+F11 to open the VBA editor and Ctrl+R for the Project Explorer (on a Mac use View > Project Explorer).
  3. Right-click VBAProject (YourFile.xlsm) and choose Insert > Class Module. It must appear under the Class Modules folder, not under Modules.
  4. Press F4 for the Properties window and change (Name) from Class1 to CEmployee. This name is the type name, and it is the only place a class is named.
  5. Paste the class code from the lab (Part 1) into the class module.
  6. Choose Insert > Module for a standard module and paste Part 2, which contains StaffDemo.
  7. Use Debug > Compile VBAProject to catch typos before running. Then click inside StaffDemo and press F5, or F8 to step through it and watch the object's fields in View > Locals Window.
Prefix class names with a capital C, as in CEmployee or CInvoice, and fields with a lower-case m, as in mSalary. It is only a naming convention, but it makes code easier to scan: you can see at a glance what is a type and what is an object's private data.

VBA editor showing a class module with properties and methods next to an Excel sheet of employees
Class modules let a macro work with its own objects, such as an employee or an invoice, instead of loose variables and parallel arrays.

Common mistakes and how to spot them

  • Class code in a standard module. Symptom: Compile error: User-defined type not defined at New CEmployee. Fix: the code must sit under Class Modules in the Project Explorer.
  • The class is still called Class1. Same symptom, same error. Fix: set (Name) in the Properties window to the exact name you use after New.
  • Forgetting Set. Symptom: run-time error 91, Object variable or With block variable not set. Fix: objects are assigned with Set emp = New CEmployee.
  • One New above the loop. Symptom: no error at all, but every item in the collection shows the last row. An object variable holds a reference, so staff.Add emp adds the same object again and again. Fix: one New per thing you want to keep, inside the loop.
  • Public variables instead of properties. Symptom: the class compiles and runs, but a negative salary is accepted. A Public Salary As Double has no place to put a check. Fix: a private field behind a Get and a Let.
  • The editor stops inside the class. Symptom: the code halts on Err.Raise although the caller has an error handler. Fix: in Tools > Options > General, set Error Trapping to Break on Unhandled Errors instead of Break in Class Module.

When a class is worth it, and when it is not

Classes are not free. They add modules, names and a little ceremony, and a twenty-line formatting macro becomes harder to read if you wrap it in one. A useful test: can you name the thing with a single noun? Employee, Invoice, Order, Shipment, Logger. If the honest answer is a verb, such as "format the report", it is probably just a Sub. The clearest signal that a class will pay off is repetition: the same group of variables written out in several procedures, arrays that must be kept in step, or the same validation copied into three places. Each of those is a sign that a noun in your business is asking to become an object.

Quick reference

ItemWhat it does
Insert > Class Moduleadds a class module to the project (in the VBA editor)
F4, property (Name)names the class, which is also the name of the new type, e.g. CEmployee
Private mSalary As Doublea field: the object's own memory, hidden from other modules
Property Get / Property Letread and write a value property, e.g. x = emp.Salary / emp.Salary = 58000
Property Setwrite a property that holds an object (covered in lesson 3)
Public Sub ApplyRise(...)a method: something the object does
Err.Raise vbObjectError + 513, ...refuses bad data with your own error number and message
Set emp = New CEmployeecreates one object, always with Set
New Collection, .Add, For Eachholds many objects and loops over them
Alt+F11, Ctrl+R, F5, F8VBA editor, Project Explorer, run, step line by line

Real-world uses

  • Payroll checks. An HR analyst loads employees from a sheet into CEmployee objects, applies rise rules by team and band, and lets the class refuse impossible values before anything is written to the payroll file.
  • Invoices with lines. A CInvoice holds a collection of CInvoiceLine objects and calculates its own net, tax and gross totals, so the macro that prints invoices never repeats that arithmetic.
  • Order imports. A buyer imports a supplier CSV into COrder objects that validate dates, quantities and article numbers, then writes only clean orders and a list of rejected rows with reasons.
  • Project tracking. A CProject object knows its budget, actual cost and deadline and exposes calculated properties such as IsOverBudget and DaysLate for a status report.
  • A shared logger. A small CLogger class writes timestamped messages to a log sheet from every module, so a long macro leaves a readable trail of what it did.

What you will build in the rest of this course

This first lesson is free. The seven lessons that follow are part of the paid course, a one-time purchase of $9.90, and they take you from this first class to a macro that is split into clean, reusable modules.

Creating Your First Class. You slow down the insert-and-name routine, separate the blueprint from the instance, see why Dim ... As New causes surprises, and learn what it really means that objects are references.

Properties: Get, Let and Set. You put private fields behind public properties, build read-only and calculated properties, and use Property Set for properties that hold other objects, with the two rules that catch everyone out.

Methods: Giving the Object Something to Do. You write methods that read well from the outside, choose between Public, Private and Friend, decide what should be a method and what a property, and deal honestly with the fact that VBA classes have no constructor with arguments.

Class_Initialize and Class_Terminate. You use the two events every class gets for free, see what Initialize is really for, learn when Terminate actually fires, and avoid the traps that come with both.

Collections of Objects. You keep many objects in a Collection, look them up by key, see what Collection cannot do, and switch to Scripting.Dictionary when you need to test whether a key exists.

A Worked Example: Invoice and Lines. You build two classes that know about each other, decide which one owns what, and end with twelve readable lines that create and total a complete invoice.

Splitting a Big Macro Into Modules. You reorganise a long macro into a layout that scales, turn the entry point into a table of contents, gather magic strings into one module, and follow a few rules that keep the project clean.

Summary

A class module defines your own object type. Its data sits in private fields, other code reaches it through properties that can refuse bad values, and its behaviour lives in methods. Compared with parallel arrays, one object per employee cannot drift out of step, travels as a single argument and enforces its rules for every caller. In the lab, that is why 14 rows become 12 clean employees, 2 clear refusals and a payroll of 767,535.50 that you can check with =SUM(D2:D13). Scroll up, build CEmployee and run StaffDemo, then try the three one-minute changes in the lab and answer the quick check question.

Frequently asked questions

What is a class module in Excel VBA?

A class module is a special kind of VBA module that defines your own object type. It holds private data, exposes properties to read and write it, and contains methods that act on it, just like Excel's own Range or Worksheet objects.

What is the difference between a module and a class module in VBA?

A standard module holds procedures you call directly and has one shared copy of its variables. A class module is a blueprint: you create objects from it with New, and each object has its own copy of the data.

When should I use a class module instead of arrays?

Use a class when several pieces of data belong to one thing, such as an employee or an invoice, and you keep them in parallel arrays, pass them together or validate them in several places. For short, one-off macros a class is usually not worth it.

How do I name a class module in VBA?

Select the class module in the Project Explorer, press F4 to open the Properties window and change the (Name) property. That name becomes the type name you use after New, for example Set emp = New CEmployee.

Why do I get "User-defined type not defined" with my class?

Usually the code was pasted into a standard module instead of a class module, or the class still has its default name such as Class1. The class must sit under Class Modules and its name must match the name after New exactly.

What is the difference between Property Let and Property Set?

Property Let assigns a plain value such as a number or text, while Property Set assigns an object, such as a Range or another class instance. Both run code when the property is written, so both can validate the value.

Keep going: Class Modules & Structure

This free lab is lesson 1 of 8. Unlock the other 7 hands-on labs, the final exam and your certificate for a one-time $9.90.

  1. Creating Your First Class
  2. Properties: Get, Let and Set
  3. Methods: Giving the Object Something to Do
  4. Class_Initialize and Class_Terminate
  5. Collections of Objects
  6. A Worked Example: Invoice and Lines
  7. Splitting a Big Macro Into Modules

Buy course โ€” $9.90 See the full course

Knowledge check

A colleague moves Set emp = New CEmployee above a loop that sets emp.FullName and calls staff.Add emp five times. What does the Collection hold afterwards?

Continues in this course
  • Creating Your First Class
  • Properties: Get, Let and Set
  • Methods: Giving the Object Something to Do
  • Class_Initialize and Class_Terminate
  • Collections of Objects
  • A Worked Example: Invoice and Lines

Buy the course to unlock the remaining 7 lessons, the exam and the certificate.

Buy course โ€” $9.90