Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 438
André Chalella Avatar asked May 14 '12 16:05

André Chalella


2 Answers

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)
like image 181
Alex K. Avatar answered Sep 29 '22 11:09

Alex K.


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
like image 45
JustinFromTexas Avatar answered Sep 29 '22 10:09

JustinFromTexas