views:

3826

answers:

5

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 memeory leaks?

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

+3  A: 

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.

Will Rickards
+1  A: 

If you are making a class module in VBA, for the constructor, you can use:

Private Sub class_initialize()
....
End Sub

There are no destructors, since VBA is garbage collected. Just make sure to clean up any circular references, and you should avoid any possible memory leaks.

Colin
+2  A: 

It's been a while since I've used them, but I don't think you can pass parameters into the constructors. I think that was one of the problems I ran into, but I was running into so many issues of how thse classes worked and how I expected them to work that I may be misremembering.

greg
You're right. You can't.
Tmdean
More complicated classes will often have "Start"-type functions and a "objectStarted" state variables to accommodate the principle of a parameterised constructor.
Joel Goodwin
+1  A: 

This might be helpful: MSDN on VB constructors

But I'm not sure if it also is for VBA cause I get: "Compile error: Expected: identifier" on the "New" keyword, when I try it in Excel. (I am always confused with what is VB VBScript VB6 VBA and VB.NET.........)

Matthijs Wessels
+1  A: 

There exists Class_Terminate which is pretty much the same as destructor.

TechnoS