首页 > 解决方案 > vba中的面向对象编程和卷影复制问题

问题描述

我最近正在研究一个基于 VBA 的大型项目,该项目需要构建许多类。突然发现set object = other object默认是shadow copy,这是我继续下去的最大问题。我需要使用对象来初始化其他对象并在对象内部更改这些对象,但不希望更改原始对象。在其他语言中,如 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 =辛特(字符串)。你有什么建议吗?可能我构造代码的方式是错误的。

标签: vba

解决方案


推荐阅读