André Chalella
André Chalella

Reputation: 14112

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?

Upvotes: 7

Views: 4441

Answers (2)

JustinFromTexas
JustinFromTexas

Reputation: 11

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

Upvotes: 1

Alex K.
Alex K.

Reputation: 175876

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)

Upvotes: 7

Related Questions