Excel VBA object constructor and destructor

家住魔仙堡 提交于 2019-12-04 15:20:33

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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




回答5:


I confirme that class_initialize and class_terminate.

You can check it by writting this TestClass:

Public testVar As Integer

Private Sub class_initialize()
    Debug.Print "Class init"
    testVar = 10
End Sub

Private Sub class_terminate()
    Debug.Print "Class terminate"
End Sub

And write this code in a module :

Sub test()
   Dim myTestClass As New TestClass
   Debug.Print myTestClass.testVar
End Sub

And then you will see logs in Debug window. But with this test, we can see that class_initialize isn't called when you create the instance (with new) but only at the first call of a methode in the instance or getting a var value.

The class_terminate seems to be called at the end of the testModule (If an instance is maked on Thisworkbook object, terminate is "never" called... probably only when the workbook is closed or when Excel is closed)



来源:https://stackoverflow.com/questions/571327/excel-vba-object-constructor-and-destructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!