Search code examples
vbapass-by-reference

ByRef not working in VBA with value type from a class


I always used ByRef successfully, until now. I need a function to modify a Double from a class-object. To illustrate, consider the following program.

Class1.cls:
Public d As Double
Sub Test()
    Dim c As Class1, d As Double
    Set c = New Class1

    c.d = 5
    d = 5

    ChangeVar c.d
    ChangeVar d

    Debug.Print c.d
    Debug.Print d
End Sub

Sub ChangeVar(ByRef d As Double)
    d = 10
End Sub

For my surprise, the above example will output

5
10

Anybody?


Solution

  • Under the hood aClassInstance.publicVariable is encapsulated as a hidden property get/let pair, so passing ByRef is passing the address of the hidden get properties return value, not the underlying variable declared in the class.

    You can test this by examining the addresses of the 2 forms of d within the class; they will be different

    (class_init)
    debug.? " d address=" & VarPtr(d)
    debug.? ".d address=" & VarPtr(me.d)