VBA - 是否可以将对象的 属性 作为参数传递给方法?

VBA - Is it possible to pass an Object's property as an argument in a method?

我已经很习惯 VBA,不过对于 Objects 不是很习惯,我现在正在碰壁...

我的配置 class 有将近 100 个属性,所以我不会在这里发垃圾邮件,因为细节对我的问题来说并不重要。

希望编写一个重复的函数从一个对象创建多个对象,然后为每个新对象的特定属性分配不同的值objects(向配置添加新元素,因此它会生成新配置),看起来像这样:

Public Function Duplicate(SrcCfg As Config, PropertyName As String, Properties As String) As Collection
Dim Cc As Collection, _
    Cfg As Config, _
    TotalNumber As Integer, _
    A() As String

Set Cc = New Collection
A = Split(Properties, "/")
TotalNumber = UBound(A)

For i = 0 To TotalNumber
    'Create a copy of the source object
    Set Cfg = SrcCfg.Copy
    'Set the property for that particular copy
    Cfg.PropertyName = A(i)
    'Add that copy to the collection
    Cc.Add ByVal Cfg
Next i

    Duplicate = Cc
End Function

但我不确定集合是否是最好的输出(因为我会获取结果并将它们合并到另一个主集合中),所以我愿意接受建议。

而且我很确定 我们不能将 属性 作为参数传递 (我花了很多时间寻找解决方案.. .) 而且我不知道该怎么做,因为这对我来说非常实用。因此,如果有解决方案或解决方法,我会很乐意尝试!

这是我的其余方法:

Friend Sub SetConfig(SrcConfig As Config)
    Config = SrcConfig
End Sub

Public Function Copy() As Config
    Dim Result As Config
    Set Result = New Config
    Call Result.SetConfig(Config)
    Set Copy = Result
End Function


复制对象的最终代码:


工作顺利:

Private Cfg As Config

Friend Sub SetConfig(SrcConfig As Config)
    Set Cfg = SrcConfig
End Sub

Public Function Copy() As Config
    Dim Result As Config
    Set Result = New Config
    Call Result.SetConfig(Cfg)
    Set Copy = Result
End Function

Public Function Duplicate(PropertyName As String, Properties As String) As Collection
Dim Cc As Collection, _
    Cfg As Config, _
    TotalNumber As Integer, _
    A() As String

Set Cc = New Collection
A = Split(Properties, "/")
TotalNumber = UBound(A)

For i = 0 To TotalNumber
    'Create a copy of the source object
    Set Cfg = Me.Copy
    'Set the property for that particular copy
    CallByName Cfg, PropertyName, VbLet, A(i)
    'Add that copy to the collection
    Cc.Add Cfg
Next i

    Set Duplicate = Cc
End Function

您实际上是对的,包括类型 (String)。

只需更换您的

Cfg.PropertyName = A(i)

CallByName Cfg, PropertyName, vbLet, A(i)

属性 名称必须作为字符串传递,而不是引用或 lambda 或其他任何东西,因此这里没有类型安全或编译器帮助。如果拼错名称,将出现运行时错误。

至于 return 类型,VBA 没有列表,所以集合通常没问题,但是因为在你的特定情况下你提前知道你将有多少个对象 returning,可以声明一个数组:

Dim Cc() As Config
ReDim Cc(1 to TotalNumber)

你可以在任何情况下声明一个数组,但如果你不知道总数,你将在每次迭代时重新分配它。