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.
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 mSalaryis the field. Outside the class it does not exist, so the only way in is through the property.Property Get Salaryruns when code readsemp.Salary.Property Let Salaryruns when code writesemp.Salary = 58000. From outside, both look like a plain variable.Err.Raisein the Let is the payoff. The check is written once, and every caller, including code someone adds next year, goes through it.IsJunioris 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.ApplyRiseis 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.
| Row | Employee | Team | Input salary | What the class does | Salary on the sheet |
|---|---|---|---|---|---|
| 1 | Anna Keller | Sales | 58,000 | junior, 3% rise | 59,740.00 |
| 2 | Marco Rossi | Finance | 72,000 | kept | 72,000.00 |
| 3 | Lea Studer | Support | 49,500 | junior, 3% rise | 50,985.00 |
| 4 | Tom Brunner | Sales | 61,000 | kept | 61,000.00 |
| 5 | Sofia Vogt | Support | 55,250 | junior, 3% rise | 56,907.50 |
| 6 | Jonas Meier | IT | -4,200 | refused: A salary cannot be negative | - |
| 7 | Nina Frei | Finance | 83,500 | kept | 83,500.00 |
| 8 | David Huber | IT | 67,800 | kept | 67,800.00 |
| 9 | (empty) | Sales | 51,000 | refused: A name cannot be empty. | - |
| 10 | Elena Graf | Marketing | 57,400 | junior, 3% rise | 59,122.00 |
| 11 | Lukas Baumann | IT | 59,900 | junior, 3% rise | 61,697.00 |
| 12 | Mia Schmid | Marketing | 64,300 | kept | 64,300.00 |
| 13 | Paul Wyss | Support | 52,800 | junior, 3% rise | 54,384.00 |
| 14 | Clara Roth | Finance | 76,100 | kept | 76,100.00 |
| Total | 12 kept, 2 refused | 757,550 | 6 juniors raised | 767,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.
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.
| Cell | Formula | Result |
|---|---|---|
| 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.03 | 9,985.50, the cost of the rises |
How to build it in Excel, step by step
- 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. - Press
Alt+F11to open the VBA editor andCtrl+Rfor the Project Explorer (on a Mac use View > Project Explorer). - Right-click VBAProject (YourFile.xlsm) and choose Insert > Class Module. It must appear under the Class Modules folder, not under Modules.
- Press
F4for the Properties window and change (Name) fromClass1toCEmployee. This name is the type name, and it is the only place a class is named. - Paste the class code from the lab (Part 1) into the class module.
- Choose Insert > Module for a standard module and paste Part 2, which contains
StaffDemo. - Use Debug > Compile VBAProject to catch typos before running. Then click inside
StaffDemoand pressF5, orF8to step through it and watch the object's fields in View > Locals Window.
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.
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 empadds the same object again and again. Fix: oneNewper 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 Doublehas 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.Raisealthough 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
| Item | What it does |
|---|---|
| Insert > Class Module | adds 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 Double | a field: the object's own memory, hidden from other modules |
Property Get / Property Let | read and write a value property, e.g. x = emp.Salary / emp.Salary = 58000 |
Property Set | write 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 CEmployee | creates one object, always with Set |
New Collection, .Add, For Each | holds many objects and loops over them |
Alt+F11, Ctrl+R, F5, F8 | VBA editor, Project Explorer, run, step line by line |
Real-world uses
- Payroll checks. An HR analyst loads employees from a sheet into
CEmployeeobjects, 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
CInvoiceholds a collection ofCInvoiceLineobjects 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
COrderobjects that validate dates, quantities and article numbers, then writes only clean orders and a list of rejected rows with reasons. - Project tracking. A
CProjectobject knows its budget, actual cost and deadline and exposes calculated properties such asIsOverBudgetandDaysLatefor a status report. - A shared logger. A small
CLoggerclass 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.
- 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
- Splitting a Big Macro Into Modules