【发布时间】: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
【问题讨论】:
-
也许可以在这里看到 Scott 的回答:stackoverflow.com/questions/4805475/…
-
@TimWilliams :谢谢,我从这个答案开始,创建
.copy方法,它确实非常有用!
标签: vba object methods properties