Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA Custom Objects Guide

· 7 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Excel VBA custom objects are a powerful way to bundle data, properties, and methods into a single, reusable structure. This allows you to create robust, object-oriented automation that is far cleaner and more maintainable than standard subroutines or functions. To achieve this, you must first define a class module, which acts as the blueprint for your object, and then create an instance of that object within your main code.

What You'll Need

  • Microsoft Excel installed on your computer.
  • A working knowledge of the VBA Editor (Alt + F11).
  • A basic understanding of data types, variables, and subroutines.

Step-by-Step

  1. Open the VBA Editor by pressing Alt + F11 on your keyboard. If the editor does not open, you can find it via the Developer tab on the Excel ribbon. On some versions, you may need to enable the Developer tab first through Excel Options.
  2. Create a New Class Module. In the VBA Editor, go to the Insert menu and select Class Module. This will create a new window, usually named Class1, which is where you will write the code for your custom object.
  3. Give Your Object a Name. In the Properties window (View > Properties Window or F4), locate the (Name) property. Change the default name (e.g., Class1) to something descriptive, such as clsInventoryItem. This is the name that will be used to reference your object throughout your code.
  4. Define Properties for Your Object. Properties are the data that your object will hold. In the class module code window, declare your properties using the Public keyword. For example, to create a property for an item's name and quantity, you would write:
    Public ItemName As String
    Public ItemQuantity As Integer
  5. Add Custom Methods. Methods are the actions that your object can perform. You can define these as Public Sub procedures within the class module. For a simple inventory object, you might add a method to reduce the quantity of an item. Add the following code to your class module:
    Public Sub ReduceQuantity(DecreaseAmount As Integer)
        If ItemQuantity - DecreaseAmount > 0 Then
            ItemQuantity = ItemQuantity - DecreaseAmount
        Else
            MsgBox "Not enough stock available."
        End If
    End Sub
  6. Create a Property Procedure. A property procedure is a more advanced way to define properties that can have logic behind them, such as automatically updating a related field. For example, you could create a property for the price that automatically calculates the total value when the quantity changes. Add this to your class module:
    Private pPrice As Double
    Public Property Get Price() As Double
        Price = pPrice
    End Property
    Public Property Let Price(ByVal vNewValue As Double)
        If vNewValue < 0 Then
            MsgBox "Price cannot be negative."
        Else
            pPrice = vNewValue
        End If
    End Property
  7. Initialize the Object. You can set up default values when the object is first created using the Class_Initialize event. Add this code to your class module to automatically set the quantity to zero when a new instance is created:
    Private Sub Class_Initialize()
        ItemQuantity = 0
        ItemName = ""
    End Sub
  8. Create a Reference for Your Object. The class module itself is just a definition. You need to create an instance of your object in your main workbook code. Open the ThisWorkbook object in the Project Explorer on the left side of the VBA Editor, double-click it, and enter the following code to create a collection of your custom objects in the Workbook_Open event, which runs automatically when the workbook is opened:
    Private Sub Workbook_Open()
        Dim myInventory As New Collection
        Dim newItem As clsInventoryItem
    
        ' Create and add items to the collection
        Set newItem = New clsInventoryItem
        newItem.ItemName = "Widget A"
        newItem.ItemQuantity = 50
        newItem.Price = 5.99
        myInventory.Add newItem
    
        Set newItem = New clsInventoryItem
        newItem.ItemName = "Gadget B"
        newItem.ItemQuantity = 25
        newItem.Price = 12.50
        myInventory.Add newItem
    
        ' Display the total value of the inventory
        Dim totalValue As Double
        Dim i As Integer
        For i = 1 To myInventory.Count
            totalValue = totalValue + (myInventory(i).ItemQuantity * myInventory(i).Price)
        Next i
    
        MsgBox "Total inventory value is: " & Format(totalValue, "Currency")
    End Sub
  9. Run Your Code. Save your workbook and close the VBA Editor. When you open the Excel file again, the Workbook_Open event will trigger. You should see a message box displaying the calculated total value of your custom objects' data.

Common Mistakes

  • Using Private Variables for Properties. A common error is defining the properties in the class module as Private. This will make the data inaccessible from the code that creates the object. Always use the Public keyword to make properties and methods available for use.
  • Not Using a Class Name. Failing to rename the class module from Class1 to something meaningful can make your code difficult to read and maintain, especially if you have multiple custom objects in the same project.
  • Forgetting to Create an Instance. The class module is only a template. You must use the Dim statement followed by New to create an actual object instance in your main code, or the object will not exist.
  • Improper Error Handling. Not including checks for negative numbers or zero values in your methods and properties can lead to errors in your data or unexpected behavior in your calculations. Always validate your inputs.

Tips

  • Use Collections of Custom Objects. Collections are a great way to manage multiple instances of your custom object in a single, ordered list, making it easy to loop through and perform actions on all of them.
  • Document Your Object. Add comments to your class module to explain the purpose of each property and method, and what it expects as input. This will make your code much easier for you and others to understand in the future.
  • Leverage Property Let/Get. While simple variables are useful, property procedures allow you to add validation logic. For example, you can check if a price is negative before setting it, ensuring your data is always correct.
  • Use Events. The Class_Terminate event can be used to perform cleanup tasks, such as saving data to a file or releasing system resources, when the object is no longer needed.

Troubleshooting

If your code is not behaving as expected, check the following common issues. The most frequent cause of problems is that the object is not being created correctly, or the properties are not being set.

  • The Object is Not Recognized. If you get a runtime error saying that the object name is not defined, check that you have created the class module and given it a name, and that you are using that exact name when you declare the object variable.
  • Properties Are Not Being Set. If you declare an object variable but cannot set its properties, ensure that the properties in the class module are declared as Public. Private properties are only visible within the class module itself.
  • Value is Not Updating. If you change a property in the class module but the value does not update in your code, check that you are referencing the correct instance of the object. If you re-declare the variable, it creates a new, empty instance.
  • Compile Errors. Syntax errors in the class module will prevent the entire project from compiling. The VBA Editor will highlight the line with the error. Fix the syntax, such as missing colons or incorrect function names, and the error should disappear.

Frequently Asked Questions

  1. What is the difference between a class module and a standard module? A standard module holds general-purpose subroutines and functions that can be called from anywhere in your project. A class module is a blueprint for creating custom objects that can hold data and perform actions, encapsulating both state and behavior.
  2. Can I use custom objects in UserForms? Yes, you can. You can create an instance of your custom object in the code behind a UserForm and use it to populate the form's controls or to perform actions when the form is closed.
  3. How do I pass a custom object to a function? You can pass a custom object to a function or subroutine just like any other variable. For example, you could write a function that takes a clsInventoryItem object as an argument and returns the total value of that specific item.
  4. Why does my code run slower with custom objects? Creating and managing custom objects can add a small amount of overhead compared to using simple variables. However, the benefits in terms of code organization and maintainability usually outweigh this performance difference, especially for complex projects.
  5. Can I save a custom object to a file? You cannot directly save a custom object to a file. You must write the values of its properties to a text file, an XML file, or a database. When you read the file back, you can create a new instance of the object and set its properties to the values you saved.
  6. Is it possible to create a custom object without a class module? No, the class module is the fundamental building block for creating custom objects in VBA. It provides the template that defines what the object is and how it behaves.