Excel VBA class modules and standard modules serve different purposes in organizing and reusing code. A standard module holds procedures and variables accessible globally, while a class module defines custom objects with properties, methods, and events, enabling encapsulation and instance-based programming. Understanding when to use each helps build maintainable, scalable Excel applications.
What You'll Need
- Microsoft Excel (2010 or later recommended for full VBA editor support)
- Basic familiarity with the VBA editor (accessed via Alt + F11)
- Knowledge of writing Sub and Function procedures in standard modules
Step-by-Step
- Open the VBA editor by pressing Alt + F11 in Excel.
- To insert a standard module, right-click VBAProject (YourWorkbookName), choose Insert, then Module. This creates a standard code module.
- In the standard module, write a simple procedure like:
Public Sub GreetUser()
MsgBox "Hello, user!" End Sub
This procedure can be called from anywhere in the workbook using GreetUser. - To insert a class module, right-click VBAProject (YourWorkbookName), choose Insert, then Class Module. This creates a class module (default name Class1).
- In the class module, rename it to something meaningful like "Person" in the Properties window (press F4 to show it).
- Define a private variable to store data:
Private pName As String - Create a property to let others read and write the name:
Public Property Let Name(value As String)
pName = value End Property Public Property Get Name() As String Name = pName End Property - Add a method that uses the stored data:
Public Sub Introduce()
MsgBox "Hello, I am " & pName & "." End Sub - Return to a standard module and create instances of your class:
Sub UsePersonClass()
Dim p As Person
Set p = New Person p.Name = "Alice" p.Introduce End Sub - Run the UsePersonClass procedure (place cursor inside it and press F5). You’ll see a message box with the greeting.
- To demonstrate encapsulation, try accessing pName directly from the standard module (e.g., p.pName). You’ll get a compile error because it’s private—this protects internal data.
- Optional: Add a Class_Initialize event to set default values when an instance is created:
Private Sub Class_Initialize() pName = "Unknown" End Sub - Optional: Add a Class_Terminate event to clean up resources (though rarely needed in simple Excel VBA):
Private Sub Class_Terminate() Debug.Print "Person object being destroyed" End Sub
Common Mistakes
- Trying to instantiate a standard module as an object (e.g., Dim m As Module1: Set m = New Module1) — this fails because standard modules are not classes and cannot be instantiated.
- Declaring variables as Public in a class module when they should be private with Property procedures — this breaks encapsulation and allows invalid values.
- Forcing early binding by declaring As Person without setting a reference to the project — while late binding (As Object) works, early binding requires the class to be public and visible, which it is by default in the same project.
- Not cleaning up circular references (e.g., two objects referencing each other) — though rare in Excel VBA, it can prevent memory release; set objects to Nothing when done.
- Assuming class modules can be used like standard modules for global functions — they cannot be called directly without creating an instance.
Tips
- Use standard modules for utility functions, global constants, or procedures that don’t rely on instance data (e.g., math helpers, file I/O wrappers).
- Use class modules when you need multiple instances with independent data (e.g., multiple Employee objects, each with their own name, ID, salary).
- Leverage Property Get/Let/Set to validate input — for example, ensure an Age property only accepts values between 0 and 120.
- Name your classes clearly (e.g., clsCustomer, clsReportBuilder) to distinguish them from standard modules in the Project Explorer.
- If you find yourself passing many related parameters to a procedure, consider grouping them into a class instead.
- Use the IntelliSense drop-down in the VBA editor to discover available properties and methods when working with class instances — it only appears if you’ve defined them properly.
- For collections of objects, combine a class module with a Collection or Dictionary in a standard module to manage multiple instances (e.g., a collection of Person objects).
Troubleshooting
- "User-defined type not defined" error when using As Person: Ensure the class module is named correctly and is not marked as Private (check the Instancing property in the Properties window — it should be PublicNotCreatable or GlobalMultiUse, which is default for class modules).
- "Object variable or With block variable not set" (Error 91): You forgot to use Set when assigning a new instance (e.g., Dim p As Person: p = New Person is wrong; must be Set p = New Person).
- Changes to the class module not reflecting: Save your workbook (Ctrl + S) — the VBA editor doesn’t always auto-save code changes.
- IntelliSense not showing class members: Make sure you declared the variable with the correct type (Dim p As Person, not Dim p As Object) and that you’re in a procedure, not the declarations section.
- Getting unexpected results from a property: Double-check that your Property Let and Property Get procedures are correctly paired and operate on the same private variable.
Frequently Asked Questions
Can I use a class module to create a custom worksheet function?
No, only public Function procedures in standard modules can be used as worksheet functions (UDFs). Class modules cannot be accessed directly from Excel formulas.
Should I make all my variables in a class module Public for simplicity?
No — exposing variables directly breaks encapsulation. Use Property procedures to control how data is read or changed, allowing validation and future changes without breaking existing code.
Is there a performance difference between standard modules and class modules?
For simple procedures, the difference is negligible. Class instances have a small overhead due to object creation, but this is rarely a concern in typical Excel VBA applications unless creating thousands of objects in tight loops.
Can I inherit from a class module in VBA like in other languages?
No, VBA does not support inheritance. You cannot create a subclass that extends another class module. For code reuse, consider composition or placing shared code in a standard module.
Do I need to terminate class objects manually?
In most cases, no — VBA’s garbage collector will release objects when they go out of scope. Setting them to Nothing is good practice in long-running loops or when referencing external resources, but not strictly required for simple data-holding classes.
Can a class module raise events that standard modules can respond to?
Yes — you can define custom events in a class module using Public Event, raise them with RaiseEvent, and handle them in a standard module using WithEvents and a variable declaration.