vba中的面向对象编程和卷影复制问题

vba中的面向对象编程和卷影复制问题,vba,Vba,我最近正在从事一个基于VBA的大型项目,该项目需要构建许多类。 突然,我发现set object=other对象在默认情况下是卷影复制,这是我继续操作的最大问题。我需要使用对象来初始化其他对象,并在对象内部更改这些对象,但不希望更改原始对象。在其他语言中,像C++一样,这很容易实现,只需在对象内部创建一个成员变量,然后做深拷贝。但是,在vba中,设置对象时默认为阴影复制。我在网上搜索了很多资源,这些资源教你如何手动进行深度复制,我认为这对于一个较小的项目很好。我的代码中有很多这样的逻辑需要实现深

我最近正在从事一个基于VBA的大型项目,该项目需要构建许多类。 突然,我发现set object=other对象在默认情况下是卷影复制,这是我继续操作的最大问题。我需要使用对象来初始化其他对象,并在对象内部更改这些对象,但不希望更改原始对象。在其他语言中,像C++一样,这很容易实现,只需在对象内部创建一个成员变量,然后做深拷贝。但是,在vba中,设置对象时默认为阴影复制。我在网上搜索了很多资源,这些资源教你如何手动进行深度复制,我认为这对于一个较小的项目很好。我的代码中有很多这样的逻辑需要实现深度复制

实际上,我不想问如何在对象方面进行深度复制,因为我认为资源已经教会了我。我只是问你什么时候需要在vba中做一个需要使用很多类的大项目。你是如何处理这类问题的

我尽可能多地做个榜样

Class Risk ' for simplification, just let Risk has one member variable and it's public so i don't need to write another method in order to change the value
public value as double


Class Profile    

dim reportingRisks As Collection ' is a collection of a class risk
dim profileShocks As Collection
sub init() 'this is used to initialize the member variables like reportingRisks in class Profile 
...
end sub

Class Asset
Dim reportingRisks as Collection
Dim profileShocks as Collection   
sub init(aProfile as Profile, str as string) ''this is used to initialize the member variables in Asset class, in this part, we need to use information both in aProfile and str to initialize and we want aProfile are same each time, str would be different
set reportingRisks = aProfile.reportingRisks
' then based on the information from str, the element in the reportingRisks would change
reportingRisks(0).value = cint(str)
end sub


'Then in the main sub
sub main()
dim assets as new collection
dim theProfile as new Profile
theProfile.init
dim str as variant
str = readsomefile() ' assume this str is assigned by reading the a multiple lines file and it becomes a array, each element is a number
dim temp as variant
dim ass as Asset
for each temp in str
set ass = new Asset
ass.init theProfile, temp ' I pass theProfile into this Procedure, and cause the temp is different, so the element in theProfile like reportingRisks will change everytime, but I don't want it change.
assets.add ass
next temp
end sub

这只是一个非常简单的例子,在这个项目中有很多这样的过程,我不想因为函数或子函数中的参数改变而改变原始参数,比如reportingRisk(0)。value=cint(str)。你有什么建议吗?可能我构造代码的方式是错误的。

我不确定我是否完全理解您的需要。英语不是我最好的一点。。。因此,如果您有一个类,比如说,
clsFoo
,您可以这样使用它:
Dim myFoo作为新的clsFoo
。是否不仅要使用
clsFoo
现有方法,还要添加新方法?你在寻找扩展方法吗?@FaneDuru我是说还有另一个类,比如说
clstemp
clsFoo
的成员变量。我已经用很多属性初始化了
clstemp
。然后我想传递
clstemp
来初始化
myFoo0、myFoo1、myFoo2
等,它们是
clsFoo
类的实例。我想在类内更改
clstemp
,它们不会相互影响。我不确定这在VBA中是否可行。至少,我不知道该怎么做……快乐冰,你能提供一个答案吗?如果我们讨论的是在过程之间传递对象,那么我们将显式地传递它们,而不是
ByVal
。但是你的用例还不清楚…@Cindymister,嗨Cindy,我试着编一个例子并把它添加到我的问题中。这有用吗?