VBA-是否可以传递对象';属性作为方法中的参数?
我已经很习惯VBA了,但对对象来说不太习惯,我现在碰到了一堵墙 我的config类有将近100个属性,所以我不会在这里发布它们,因为细节对我的问题并不重要 我希望编写一个重复的函数,从一个对象创建多个对象,然后为每个新对象的特定属性指定不同的值(向配置中添加新元素,以便生成新配置),如下所示:VBA-是否可以传递对象';属性作为方法中的参数?,vba,object,methods,properties,Vba,Object,Methods,Properties,我已经很习惯VBA了,但对对象来说不太习惯,我现在碰到了一堵墙 我的config类有将近100个属性,所以我不会在这里发布它们,因为细节对我的问题并不重要 我希望编写一个重复的函数,从一个对象创建多个对象,然后为每个新对象的特定属性指定不同的值(向配置中添加新元素,以便生成新配置),如下所示: Public Function Duplicate(SrcCfg As Config, PropertyName As String, Properties As String) As Collectio
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)
与
属性名必须作为字符串传递,而不是引用、lambda或其他任何内容,因此这里没有类型安全或编译器帮助。如果拼写错误,将出现运行时错误
至于返回类型,VBA没有列表,因此集合通常是可以的,但因为在特定情况下,您事先知道要返回多少对象,所以可以声明数组:
Dim Cc() As Config
ReDim Cc(1 to TotalNumber)
你可以在任何情况下声明一个数组,但是如果你不知道数组的总数,你会在每次迭代中重新分配它。也许可以在这里看到Scott的答案:@TimWilliams:Thx,我从这个答案开始,创建
.copy
方法,它确实非常有用!谢谢你的快速回答,我喜欢读到这是可能的!我对它进行了测试,效果非常好!:)Thx用于输入,我将发布我的更新代码,以便人们在遇到一个小问题时更清楚,因为我不确定这一点,但我使用自定义对象作为参数,但它是一个对象方法,所以我可以将Set Cfg=SrcCfg.Copy
更改为Set Cfg=Me.Copy
并去掉参数吗?这看起来很合乎逻辑,但这是我第一次真正使用VBA对象
Dim Cc() As Config
ReDim Cc(1 to TotalNumber)