ByRef not working in VBA with value type from a class

▼魔方 西西 提交于 2019-12-23 09:25:57

问题


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?


回答1:


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)



回答2:


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


来源:https://stackoverflow.com/questions/10587324/byref-not-working-in-vba-with-value-type-from-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!