Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA object constructor and destructor

I need to make some custom objects in VBA that will need to reference each other and I have a some issues.

First - how do object constructors work in VBA? Are there constructors?

Second - are there destructors? How does VBA handle the end of the object lifecycle? If I have an object that references others (and this is their only reference), then can I set it to Nothing and be done with it or could that produce memory leaks?

This quasi-OO stuff is just a little bit irritating.

like image 662
notnot Avatar asked Feb 20 '09 21:02

notnot


People also ask

What is a constructor in VBA?

Mar 21, 2021 • 2 min read. If you are familiar with other object-oriented programming languages, you are likely familiar with the concept of constructors: In class-based object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object.

What is constructor and destructor in VB net?

Constructors and DestructorsA destructor is a special member Sub of a class that is executed whenever an object of its class goes out of scope. A destructor has the name Finalize and it can neither return a value nor can it take any parameters.

How do you initialize a class in VBA?

The Initialize event occurs when you: Create a new instance of a class directly by using the New keyword with the Set statement. Dimension an object variable using the New keyword and creating an instance of a class indirectly by setting or returning a property or applying a method defined in the class module.

What is the difference between a class module and a module in VBA?

The main difference between classes and modules is that classes can be instantiated as objects while standard modules cannot.


1 Answers

VBA supports Class Modules. They have a Class_Initialize event that is the constructor and a Class_Terminate that is the destructor. You can define properties and methods. I believe VBA uses reference counting for object lifecycle. Which is why you see a lot of Set whatever = Nothing in that type of code. In your example case I think it will not leak any memory. But you need to be careful of circular references.

like image 86
Will Rickards Avatar answered Sep 28 '22 03:09

Will Rickards