【问题标题】:VBA - Is it possible to pass an Object's property as an argument in a method?VBA - 是否可以将对象的属性作为方法中的参数传递?
【发布时间】:2015-10-07 10:03:34
【问题描述】:

我已经习惯了 VBA,但对 Objects 不太习惯,而且我现在正在碰壁......

我的配置类有近 100 个属性,所以我不会在这里向它们发送垃圾邮件,因为细节对我的问题并不重要。

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

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

【问题讨论】:

标签: vba object methods properties


【解决方案1】:

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

只需更换你的

Cfg.PropertyName = A(i)

CallByName Cfg, PropertyName, vbLet, A(i)

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

至于返回类型,VBA 没有列表,所以集合通常没问题,但是因为在您的特定情况下您事先知道要返回多少个对象,您可以声明一个数组:

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

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

【讨论】:

  • 感谢您的快速回答,我喜欢阅读它是可能的!
  • 我对其进行了测试,效果非常好! :) 谢谢输入,我会发布我更新的代码,以便人们来时更清楚
  • 只是一个小问题,因为我不确定,但我使用自定义对象作为参数,但它是一个对象方法,所以我可以将 Set Cfg = SrcCfg.Copy 更改为 Set Cfg = Me.Copy 并得到摆脱争论?这似乎很合乎逻辑,但这是我第一次真正使用 VBA 对象
猜你喜欢
  • 1970-01-01
  • 2011-11-30
  • 2017-08-01
  • 2010-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-05
相关资源
最近更新 更多