No Constructors in VBA

When it comes to building Classes, VBA does not support the use of Constructors. A Constructor is method within a class that gets executed when a class is first instantiated. Constructors are particularly useful when working with objects, because they allow for variables to be passed to a class before it is first used. Languages like Java and C# allow you to define multiple constructors, which can take in any number of different data type variables. The closest thing VBA has to a constructor is a class initialize event. However, this method does not accept any arguments. Let’s look at some code to highlight this, the code below shows a simple class for a car:

When an object is created using this class, the class internally sets the colour of the car to be red when created. If we wanted to create a Car object which was blue, we would have to set its colour property to blue after creation:

But what if we wanted to do this before it is first used? One workaround for this would be to not call the Car class directly, but instead create another class whose sole responsibility is to create Car objects. The following class called csCreator is an example of such a class:

So now if we wanted to create a blue Car object and ensure it is blue at the point in which it is first instantiated we would do the following:

Having a dedicated class that only creates other classes, allows us to add different methods for creating Car objects. So in effect we can mimick the functionality of the Car class having a constructor method. We can do this as long as the original class exposes properties that can be adjusted. Hopefully, this proves to be a nice workaround for your own VBA projects.

Thank you for reading this post. Please take time to read the disclaimer about content found on this site.

Share :Facebooktwitterredditpinterestmail