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?
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)
Just ran into this issue myself, its cleaner workaround is turning it into a function
Sub Test()
Dim c As Class1, d As Double
Set c = New Class1
c.d = 5
d = 5
c.d = ChangeVar(c.d)
d = ChangeVar(d)
Debug.Print c.d
Debug.Print d
End Sub
Public function ChangeVar(d As Double)
ChangeVar = 10
End Function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With