ByRef does not work in VBA with type value from class

I have always used ByRef successfully, so far. I need a function to change Double from an object class. 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 cd = 5 d = 5 ChangeVar cd ChangeVar d Debug.Print cd 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 

Is anyone

+6
source share
2 answers

Under the hood, aClassInstance.publicVariable encapsulated as a hidden get / let pair property, so ByRef passes the address of the property of hidden get properties, not the base variable declared in the class.

You can verify this by examining the addresses of two forms d inside the class; they will be different

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

Just ran into this question, its more efficient workaround turned it into a function

 Sub Test() Dim c As Class1, d As Double Set c = New Class1 cd = 5 d = 5 cd = ChangeVar(cd) d = ChangeVar(d) Debug.Print cd Debug.Print d End Sub Public function ChangeVar(d As Double) ChangeVar = 10 End Function 
+1
source

Source: https://habr.com/ru/post/915699/


All Articles