VBA Class Modules: A Step By Step Guide

In this tutorial, we will provide an introduction to VBA class modules. You can create your own custom objects by using VBA class modules.

This allows you to take advantage of concepts, associated with object-oriented programming in your VBA code.

If you would like to learn more about VBA, then we have a whole course dedicated to Excel VBA.

Did you know that an Expert Excel user is 400% more likely to have recieved formal training compared to the average user? For more Excel facts read here.

 

How Is A Class Module Different To A Normal Module?

VBA is an object-oriented programming language. When you write VBA code, you will often be manipulating objects in some way.

Excel has standard built-in objects that are available, for you to work with. These include the application object, the workbook object, and the worksheet object among others.

 

Graphic showing the common objects utilised in Excel VBA code.

 

Each of these objects have associated properties and methods.

To go over these topics in greater detail, please visit some of our previous VBA tutorials.

  1. Our Introduction to Macros article will get you up to speed with how to add the Developer Tab to the Ribbon. You will learn all about how to create simple macros in Excel. In addition, you will learn how to assign shortcut keys to macros and how to assign macros to buttons.
  2. Our Introduction to VBA article covers the VBA object model in Excel, and goes over what objects, properties and methods are. You will also learn about how to access the Visual Basic Editor. You will discover how to change the properties of objects.
  3. In our Mastering VBA Special Cells In Excel tutorial, we go over the Special Cells method in VBA, as well as the Activate, Select and Copy methods. This post will help you to get comfortable with using methods in your code. We also introduce you to Error Handling.
  4. The How to Use the COUNTA Function in Your VBA Code tutorial, covers the WorksheetFunction object. You will learn how to use the worksheet COUNTA Function and other built-in Excel worksheet functions in your VBA code.

 

Screenshot detailing all the reasons to join the Acuity Training VBA course.

 

When you insert a class module, you are creating the specifications for a custom object. VBA class modules are useful when you want to model real-world objects.

For example, let’s say a VBA developer working for a small plant nursery, wanted to create a plant object that was based on a plant class.

A plant has a common name and a scientific name. It’s life cycle can be classified as annual, perennial or biennial. It can be drought-resistant, of medium water requirements or needing to be watered constantly.

These are all the attributes that a plant has. This would be analogous to the properties of the plant object.

If the plant receives the right nutrients and conditions are optimal for growth, then the plant will grow. So, growth is analogous to a method. If the plant is a flowering plant, then the flowers will bloom at a certain time. This could be another method.

The nursery requires that each pot containing a plant be labelled, with the scientific name of the plant, its life cycle classification as well as it’s water needs. This labelling can be considered to be an action or method, associated with each plant.

A normal module on the other hand, is a place where you will store your sub procedures and functions. A normal module cannot be instantiated as a class.

 

Insert The Class Module

We are going to model the plant object that we described above, using a class module.

So, let’s look at how to insert a class module.

 

Step 1:

Press ALT-F11 on your keyboard in order to access the Visual Basic Editor.

 

Step 2:

Go to the Insert Tab and select Class Module.

 

Screenshot showing the Class Module option on the Insert Tab.

 

You should see the following.

 

Screenshot showing the Class Module which has been created.

 

Creating the Template for An Object Item

The first thing we are going to do, is choose a name for our Class. When naming the class don’t give it the name of an existing built-in object or keyword.

 

Step 1:

So, in our case we’ll name our class clPlant.

 

Screenshot showing the name of the new class.

 

    • Note: In order to view all the built-in objects at your disposal. Go to the View Tab and select Object Browser.

 

Screenshot showing the Object Browser option highlighted.

 

Now you will be able to see all the built-in objects and their associated properties and methods.

You will also be able to see the new class that we just created.

 

Screenshot showing the built-in objects and the newly created custom class.

 

You can close the window.

 

Step 2:

Enter the following code in the class module we just created.

 

Option Explicit

‘The properties
Public commonName As String
Public scientificName As String
Public classificationlifeSpan As String
Public wateringRequirements As String

‘This is the growth method
Public Sub plantGrowth()

‘We start by declaring two variables
Dim growthStatus As String
Dim growthstatusShape As ShapegrowthStatus = “is growing”

‘This line is telling Excel to read out the common name of the plant and state that the plant is growing
Application.Speech.Speak “The” & ” ” & commonName & ” ” & growthStatus

‘The message box displays the text giving the common name of the plant and saying that the plant is growing
MsgBox “The” & ” ” & commonName & ” ” & growthStatus, vbOKOnly, “This is the Growth Status of the Plant Currently”

‘We are creating a rectangle on the active sheet and specifying the position and size with this line
Set growthstatusShape = ActiveSheet.Shapes.AddShape(msoShapeRectangle, 70, 16, 170, 20)

‘We are filling the shape with a dark green colour
growthstatusShape.Fill.ForeColor.RGB = RGB(18, 90, 20)
‘We are stating the text that will be added to the shape
growthstatusShape.TextFrame.Characters.Text = “The plant is growing”
‘We are centre aligning the text in the shape
growthstatusShape.TextFrame2.TextRange.ParagraphFormat.Alignment = msoAlignCenterEnd Sub

‘This is the flower blooming method
Public Sub flowersBlooming()

‘We are declaring a variable
Dim flowerbloomingStatus As StringflowerbloomingStatus = “The flowers are blooming”

‘We are telling Excel to read out the words, the flowers are blooming
Application.Speech.Speak flowerbloomingStatus

‘The message box displays the text saying that the flowers are blooming
MsgBox flowerbloomingStatus, vbOKOnly, “This is the Flower Blooming Monitoring of the Plant Currently”

End Sub

‘This is the labelling method which is named generalInformation
Public Sub generalInformation()

‘We start by declaring two variables
Dim generalInformationText As String
Dim generalInformationShape As ShapegeneralInformationText = scientificName & Chr(13) & classificationlifeSpan & Chr(13) & wateringRequirements

‘We are creating a rectangle on the active sheet and specifying the position and size with this line
Set generalInformationShape = ActiveSheet.Shapes.AddShape(msoShapeRectangle, 70, 52.5, 170, 50)

‘Using the With…End With Construct we are changing some of the properties of this rectangle
With generalInformationShape

‘We are stating that the text that should be added to the rectangle should be the scientific name of the plant
‘the classification of it’s lifespan and it’s specific watering requirements
.TextFrame.Characters.Text = generalInformationText
‘We are filling the shape with a dark green colour
.Fill.ForeColor.RGB = RGB(18, 90, 20)
‘We are specifying that the font for the text should be in italics
.TextFrame2.TextRange.Font.Italic = msoTrue

End With

End Sub

 

Now let’s look at the code in greater detail. We start off by making four variable declarations in our class module. These will be the properties of our object. We use the Public statement.

We then create the methods of our custom object by using sub routines.

In our growth method, we are utilising the speak method of the built-in Speech object. By using this method we are able to make Excel play back the text string that we have input as an argument.

 

Screenshot showing the first portion of the code in the Class Module.

 

Screenshot showing the second portion of the code in the Class Module.

 

Use The Object!

We now want to use the custom object in our code.

 

Step 1:

To do this, go to the Insert Tab and select Module.

 

Screenshot showing the Module option on the Insert Tab highlighted.

 

Step 2:

In the module create a sub procedure called mainCode and start by using the object. Here, we use the Dim keyword in combination with the New keyword.

You will notice that as you type, Intellisense will detect the new class that we just created. Select clPlant from the menu and press Tab.

 

Screenshot showing VBA Intellisense showing the new class.

 

 

Option Explicit

Sub mainCode()

Dim plant As New clPlant

‘We are specifying that the value of the commonName property is Bellflower, for our object
plant.commonName = “Bellflower”

‘We are specifying that the value of the scientificName property is Campanula portenschlagiana, for our object
plant.scientificName = “Campanula portenschlagiana”

‘We are specifying that the value of the classificationlifeSpan property is Perennial, for our object
plant.classificationlifeSpan = “Perennial”

‘We are specifying that the value of the watering requirements property is Medium watering requirements, for our object
plant.wateringRequirements = “Medium watering requirements”

‘We are now accessing the plantGrowth method of the object
plant.plantGrowth

‘We are now accessing the flowersBlooming method of the object
plant.flowersBlooming

‘We are now accessing the generalInformation method of the object
plant.generalInformation

End Sub

 

 

Screenshot showing the code for the module.

 

Now if we wanted to create another object based on our class, called plant1 for example, we could do this. This object would have all the properties and be able to access all the methods specified, in the clPlant class.

plant1 could be used for the Magnolia plant for example.

In this way, the class is used as a template for multiple copies of the  object. You can also see that most of the difficult code is hidden from view when one is using the object in a normal module.

So let’s say more than one programmer was working on the application, they could use the custom objects in any of their modules with ease.

Looking for more on Excel? Read our guide to the XLOOKUP Function here.

 

Step 3:

Now we want to assign the mainCode macro to a shape. So, when the user clicks on the shape, the code will run.

On a blank sheet in the workbook, go to the Insert Tab and in the Illustrations Group, select the Icons option.

 

Screenshot showing the Icons option in the Illustrations Group highlighted.

 

Type plant in the Search box to see all the icons that are related to plants.

 

Screenshot showing all the icons related to the plant search term.

 

Select the filled leaf icon and click the Insert button.

 

Screenshot showing the filled leaf icon highlighted.

 

With the icon selected, go to the Graphics Format Tab and in the Change Group, select the Convert to Shape option.

 

Screenshot showing the Convert to Shape option in the Change Group, on the Graphics Format Tab highlighted.

 

Now with the shape selected. Go the Shape Format Tab, and in the Shape Styles Group, select Shape Fill.

Select the Green, Accent 6, Darker 25% fill.

 

Screenshot showing the Green, Accent 6, Darker 25% fill chosen.

 

Now right-click the shape and select Assign Macro…

 

Screenshot showing the Assign Macro...option highlighted.

 

Using the Assign Macro Dialog Box, select the mainCode macro and then click Ok.

 

Screenshot showing the mainCode macro selected.

 

Step 4:

Now make sure the shape is not selected. Then go to the View Tab and in the Show Group, uncheck the Gridlines option.

If you hover over the shape, the cursor should change.

If you press the shape. You should hear the words the Bellflower is growing, followed by a message box displaying the text.

 

Screenshot showing the message box displaying the text: the Bellflower is growing.

 

You should then hear the words the flowers are blooming spoken, followed by a message box displaying the text.

 

Screenshot showing the message box displaying the text: the flowers are blooming.

 

Excel will then create two rectangles on the worksheet. One with text stating that the plant is growing and another containing the scientific name, life span classification and watering requirements of the Bellflower plant.

 

Screenshot showing the rectangles with the text, added to the worksheet as a result of running the code.

 

Advantages and Disadvantages Of Using Class Modules

Let’s review some advantages and disadvantages of using class modules.

 

Graphic showing the advantages versus the disadvantages of using VBA Class Modules.

 

Learning Objectives

You now know how to:

  • Use a Class Module to create a custom object
  • Specify the Properties and Methods of this custom object
  • Call methods
  • Make use of the Speech.Speak method to make Excel read text out loud
  • Insert an Icon, convert it to a shape and assign a macro to the shape

Additionally, you have an understanding of:

  • What the difference between a Class Module and a Normal module is

 

Conclusion:

Class modules are useful, when you need to create your own custom objects.

If you would like to delve into advanced VBA topics such as creating Add-Ins, then you should consider learning more about class modules.

Looking for more Excel tips? Check out the Creating a Data Model in Excel article here!

Special thank you to Taryn Nefdt for collaborating on this article!

About Ben Richardson

Ben is a director of Acuity Training which he has been running for over 10 years.


He is a Natural Sciences graduate from the University of Cambridge and a qualified accountant with the ICAEW.


He previously worked as a venture capitalist and banker and so had extensive experience with Excel from building financial models before moving to learn SQL, Microsoft Power BI and other technologies more recently.