Excel VBA class modules allow you to create custom objects with their own properties and methods, making your macros reusable and easier to maintain. You need Excel installed and the Developer tab enabled in the Ribbon to create them.

What You'll Need

  • A computer running Microsoft Excel (2016 or newer is recommended for full feature support).
  • Basic familiarity with the Excel interface and the VBA Editor (Alt+F11).
  • The Developer tab enabled in the Excel Ribbon. If it is not visible, go to File > Options > Customize Ribbon and check the box next to Developer.

Step-by-Step

  1. Open the VBA Editor. Press Alt+F11 on your keyboard to open the Visual Basic for Applications editor window.
  2. Insert a New Class Module. In the VBA Editor, click on the menu bar labeled Insert from the top menu and select Class Module. A new window will appear in the editor with the title "Class1". You can rename this by changing the text in the Properties window (usually found on the right side of the editor) from "Class1" to something descriptive, like "clsCustomer".
  3. Define a Public Property. A class module is essentially a blueprint. The most basic thing you can do is define a property that holds a value. In the code window for your class module, type the following line of code to create a public property called CustomerName:
    Public CustomerName As String
    This tells Excel that any object created from this class will have a string property called CustomerName.
  4. Define a Public Property with a Let and Get procedure. While the method above works for simple values, using Let and Get allows you to add logic (like validation) when the value is set. Replace the code from the previous step with the following:
    Private pCustomerName As String
    
    Public Property Let CustomerName(ByVal value As String)
        ' Simple validation: ensure the name is not empty
        If Len(value) > 0 Then
            pCustomerName = value
        End If
    End Property
    
    Public Property Get CustomerName() As String
        CustomerName = pCustomerName
    End Property
    This creates a private backing variable pCustomerName to store the actual data and exposes a public property called CustomerName. The Property Let procedure runs when you assign a value (e.g., obj.Name = "John"), and the Property Get procedure runs when you retrieve a value (e.g., MsgBox obj.Name). The validation inside Property Let prevents you from assigning an empty string to the name.
  5. Add a Method to the Class. Methods are actions that the object can perform. Add a new subroutine to your class module to calculate a full name from the first and last name properties. Below the existing Property code, add this method:
    Public Sub CalculateFullName()
        ' This method assumes you also added properties for FirstName and LastName
        ' in the same way as the CustomerName property above.
        ' For this example, we'll use a simple string concatenation.
        If Len(pCustomerName) > 0 Then
            MsgBox "Full Name is: " & pCustomerName
        Else
            MsgBox "No name is set."
        End If
    End Sub
    This method demonstrates how a class can contain its own logic. In a more complex scenario, this method might format a date, calculate a subtotal, or send an email.
  6. Create an Instance of the Class in a Standard Module. Class modules are just blueprints. To use them, you must create an instance of the class in a standard code module. Press Alt+F11 again to ensure you are in the main VBA window. Insert a new standard module (Insert > Module) and add the following code:
    Sub CreateAndUseCustomer()
        ' This line creates a new, empty object based on our class module
        Dim objCustomer As New clsCustomer
    
        ' We can now set properties and call methods on this object
        objCustomer.CustomerName = "Jane Doe"
        objCustomer.CalculateFullName
    
        ' If we tried to set it to an empty string, the validation would prevent it
        ' objCustomer.CustomerName = ""
    End Sub
    When you run this macro, it will create a new clsCustomer object, set its name to "Jane Doe", and then display a message box with the full name.
  7. Understand the Scope of the Object. Notice that the object objCustomer is defined locally within the CreateAndUseCustomer subroutine. This means it exists only while that macro is running. Once the macro finishes, the object is destroyed and all its data is lost. To create a persistent object, declare it at the top of the module, outside any subroutine, or use a global variable.
  8. Optional: Add an Initialize Event. You can add code that runs automatically when an object is first created. In the class module, look for the Class_Initialize event procedure. If it does not exist, type it in manually. This is a great place to set default values for your properties. Add this code to the Class_Initialize event:
    Private Sub Class_Initialize()
        ' Set a default value when the object is first created
        pCustomerName = "Unknown Customer"
    End Sub
    Now, if you create a new object and do not set the CustomerName property before using it, the method CalculateFullName will return "Unknown Customer" instead of an empty string.

Common Mistakes

One common mistake is confusing the class module itself with the instance of the class. The module is the template, and the New keyword creates a specific copy. You cannot set properties directly in the class module code (except in the Class_Initialize event) because that would apply to the template, not the specific objects you create. Always use the instance variable (like objCustomer in the example) to interact with the data.

Another frequent error is trying to reference the class name directly in a standard module without declaring a variable of that type. For example, writing clsCustomer.Name = "Test" will not work. You must first declare a variable of that type, such as Dim obj As New clsCustomer, and then assign properties to the variable obj.

Tips

Always give your class modules a descriptive name starting with "cls" (e.g., clsCustomer, clsProduct). This makes it immediately clear to anyone reading your code that it is a class module and not a standard module.

Use private backing variables (with a lower case 'p' prefix) for your properties, and public Property procedures for the interface. This encapsulates your data, preventing other parts of your code from directly accessing or corrupting it. You can then add validation logic inside the Property Let procedures to keep your data clean and consistent.

Keep your class modules focused on a single concept. For example, a clsCustomer class should only handle customer-related data, not the logic for saving customers to a file. That logic should be kept in a standard module or a different class module.

Troubleshooting

If you get a Compile Error: User-defined type not defined when trying to run a macro that uses a class module, it usually means the class module has not been saved. Close the VBA Editor, save your workbook as an Excel Macro-Enabled Workbook (.xlsm), and reopen it. This is a frequent issue because class modules are not saved until the file is explicitly saved.

If your class module does not appear in the Object Browser (press F2 to open it), make sure the class module is part of the active project. If you have multiple workbooks open in the VBA Editor, select the correct workbook in the Project Explorer pane on the left side of the editor.

If you find that your properties are not retaining their values between subroutine calls, you may have declared the object variable inside the subroutine. Move the declaration of the object (e.g., Dim objCustomer As New clsCustomer) to the top of the module, outside of any subroutine, to make it a module-level variable. This ensures the object persists for the entire life of the VBA project.

Frequently Asked Questions

What is the difference between a standard module and a class module?

A standard module holds general-purpose subroutines and functions that can be called from anywhere in your project. A class module is used to create custom objects with their own properties and methods, allowing you to model real-world entities and manage their state in a structured way.

Can I pass a class module as an argument to a subroutine?

Yes, you can. You can declare a parameter in a subroutine or function as the type of your class module. For example, Sub ProcessCustomer(ByVal cust As clsCustomer). This allows you to pass a specific object instance to the routine and access its properties and methods.

How do I destroy an object created from a class module?

When you set the object variable to Nothing, the object is destroyed and the memory it was using is returned to the system. For example, Set objCustomer = Nothing. This is best practice to free up resources, especially if you are creating many objects in a loop.

Can I have more than one instance of a class module?

Absolutely. The New keyword creates a new instance every time it is used. In a loop, you can create hundreds or thousands of unique objects, each with its own set of property values.

Do class modules work in Excel Online or the Excel app on mobile devices?

No. Class modules and VBA macros are not supported in Excel Online or the Excel mobile app. They are only available in the desktop version of Microsoft Excel for Windows, macOS, and the Excel for Windows on the Web (in the browser) when the file is opened in the desktop app.

Can I use class modules to create custom functions that return a value like a worksheet function?

You cannot directly use a class module to create a user-defined function that can be typed directly into a cell (like =MyCustomFunc(A1)). Class modules are primarily used for creating objects and managing state in VBA code. If you need a custom function for a spreadsheet cell, you should create a Function in a standard module instead.