Search code examples
vbams-office

Office VBA: When are Properties processed?


I wonder when Properties are processed in Office VBA.

Consider this Class module (MyClass):

Public Property Get ExpensiveProperty() As Variant
    'Some resource expensive procedure here
End Property

Public Property Get SomeProperty() As Variant
    'Something easy
End Property

And this Module:

Sub test()
    Dim MC As MyClass
    Set MC = New MyClass
    
    Dim Smth As Variant
    Smth = MC.SomeProperty
End Sub

Is MC.ExpensiveProperty processed in test() procedure? (Assume no reference to ExpensiveProperty in SomeProperty)


Solution

  • Putting a simple Debug.Print-Statement reveals that ExpensiveProperty is not called except if requested (and I see no point why it should).

    Public Property Get ExpensiveProperty() As Variant
        Debug.Print "Expensive..."
        ExpensiveProperty = "Expensive"
    End Property
    
    Public Property Get SomeProperty() As Variant
        Debug.Print "Easy..."
        SomeProperty = "Easy"
    End Property
    

    After running your test-routine, you will find the output Easy... in the immediate window but not Expensive.... Setting a breakpoint in both getter also shows that the expensive method is not called.

    Of course that changes if you add a watch on the MC-variable or look into it in the Local-window. In the moment you click on the small [+]-button, the debugger tries to evaluate all public properties and for that of course must call all getter methods (note that in that case the debugger will not stop at any breakpoint, but the Debug.Print is executed.