VBA – Interfaces in VBA How And Why?

Interfaces in VBA are something extremely rare. So far,  as a VBA developer with about 3 years of developing experience (e.g. being paid to code, and not coding for fun) I have seen only one other developer to use classes (and this developer was probably the best developer I have worked with!).

Classes are not widely used in VBA, due to the following reasons – there is some kind of magic around them if you are a newcomer into OOP and in VBA we can easily survive without them. The only bonus that they bring us – they make our project easier to maintain and to understand.

vba

 

 

So, what are interfaces? They are the template of the class. I am really tempted to mention the word inheritance, but I will not. So, back to interfaces. Let’s say that we have three objects – a car, a dog and a planet. Quite different objects. But, we may unite them into the interface IMoveables. Each one of these objects can move. And each one would do so by its own way. Enough said, let’s try the explanation with code:

We have two types of garages – a car port and a deep garage (tg in the code below). They both have a routine called Info() and a function called CalculatePrice(ByVal dbl_price As Double) As Double. These functions are implemented in a different way – just like the planet and the dog have a different type of movement. When we call the function Info of the Deep garage we get the message “The TG are deep!” printed on our console. The same function at the car port says “The carports are cheaper than TG.”.

So, you may think that we are actually writing too much code. Why are we uniting them under one and the same interface? The simple reason with VBA is – because otherwise we may get confused. And with this interfaces, we may unite all the objects in a collection and ask each object to do its own function. With a simple loop.

Simply copy the following examples in VBA and check them:

Create a new class, name it lGeneral and paste the following:

Yes, it is true, the functions are empty! But still, they work! 🙂

Create a new class, name it clsCarport and paste the following:

Create a new class, name it clsTG and paste the following:

Create a new module, name it as you wish and paste the following:

The Test() procedure is the one that you should run, in order to get the party started! 🙂

The code of the interfaces is available in GitHub as well! 🙂

Note – here is a good example of implements from StackOverflow.

 

About

VBA Developer

Tagged with: ,