如何将 VBA 类变量传递给模块函数 ByRef?

问题描述 投票:0回答:0

VBA 类对象可以传递给模块函数,然后函数可以修改类对象的变量。

但是,我找不到一种方法来传递单个类变量来做同样的事情,即修改单个类变量

用Excel说明;

'Create a Class Module (named Class1) with One Variable;

 Public c1Long As Long

'Copy the following into a Code Module;

Public Cls1 As Class1

Function SetCls1LongTo2(ioCls1 As Class1)
    ioCls1.c1Long = 2
End Function

Function SetCls1LongTo3(ByRef ioLong As Long)
    Debug.Print "iPar=" & ioLong
    ioLong = 3
    Debug.Print "oPar=" & ioLong
End Function

现在从立即窗口运行以下命令;

Set Cls1=New Class1
Call SetCls1LongTo2(Cls1)
? Cls1.c1Long                       '2 as expected
Call SetCls1LongTo3(Cls1.c1Long)    'the Debug.Prints are "iPar=2" and "oPar=3" as expected
? Cls1.c1Long                       'still 2? 

SetCls1LongTo3()中的“ByRef”应该是多余的,我已经试过了; 我也试过在 Cls1 中为 c1Long 声明 Let 和 Get 属性,结果都是一样的

好像整个类对象都可以通过引用传递,但是单个类变量只能通过值传递?

任何人都可以解释这种行为,并希望也提供解决方案吗?

excel vba class variables pass-by-reference
© www.soinside.com 2019 - 2024. All rights reserved.