我已经习惯了VBA,对于对象来说并不是那么多,而且我现在正在撞墙...
我的配置类有近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
答案 0 :(得分:2)
你实际上做对了,包括类型(String
)。
只需更换
即可Cfg.PropertyName = A(i)
与
CallByName Cfg, PropertyName, vbLet, A(i)
属性名称必须作为字符串传递,而不是引用或lambda或任何东西,因此这里没有类型安全或编译器帮助。如果拼错名称,您将遇到运行时错误。
至于返回类型,VBA没有列表,所以集合通常很好,但因为在你的特定情况下你事先知道你将返回多少个对象,你可以声明一个数组:
Dim Cc() As Config
ReDim Cc(1 to TotalNumber)
你可以在任何情况下声明一个数组,但是如果你不知道总数,你就可以在每次迭代时重新分配它。