VBA Reference counting - Object destruction

后端 未结 2 983
离开以前
离开以前 2020-12-24 13:20

Lately I\'ve bumped into a question that made me pounder; it kept me busy and I couldn\'t find a transparent explanation for it on the net.
It is related to the destruct

2条回答
  •  甜味超标
    2020-12-24 13:32

    Good Question :)

    Excel controls the creation of its objects. Likewise it also controls their destruction.

    Setting oApp = Nothing just destroys the object reference. It doesn't remove the Application. To destroy an Excel object, you have to use it's .Quit method.

    Whenever you do, Set x = Nothing, the reference(pointer) named x to its relevant object is removed. This doesn't mean that the object itself will be removed from the memory. Whether the object will be removed from memory or not, depends on various factors.

    1. Whether there are more references pointing towards the same object. If there are, the object will not be removed. The reference count must be zero.
    2. The internal implementation of the destructor of that object.

    The .Quit method is defined to graciously remove all the memory objects excel has allocated, and close itself.

    It is similar to calling Close on a form in VB6. Take for example, a form in vb6.

    Dim f As Form
    Set f = Form1
    f.Show
    
    '
    '~~> Rest of the code
    '
    
    Set f = Nothing
    

    Will this destroy the form? :)

    FOLLOWUP

    How about question 2? Thanks – Kim Gysen 14 mins ago

    enter image description here

    It might not be exactly as shown here, and compiler optimizations may make things behave differently... but this is the basic concept that is at work.

提交回复
热议问题