Excel VBA:如何将项目添加到类中的集合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18411747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Excel VBA: How do I add an item to a collection within a class?
提问by Shari W
I have a class that contains a collection of itself. (The top level class contains summary versions of the detailed instances in the collection.)
我有一个包含自身集合的类。(顶级类包含集合中详细实例的摘要版本。)
Currently the collection is a public variable because I haven't figured out all the details of working with private variables yet. I can fix that later.
目前该集合是一个公共变量,因为我还没有弄清楚使用私有变量的所有细节。我可以稍后修复它。
How do I add items to the collection? I am getting error 91 for missing object variables.
如何将项目添加到集合中?由于缺少对象变量,我收到错误 91。
Thanks for all prior help. I have been retooling my code to use classes more extensively, and it's really great how things are cleaning up.
感谢所有先前的帮助。我一直在重组我的代码以更广泛地使用类,而且事情的清理方式真的很棒。
Class cPE
类cPE
Public PE_Details As Collection ' collection of cPE
Public PE_ID as integer
Public PE_ID_Index as integer
' Add to the detailed list of PE's
Public Function AddPEDetail(ByRef cPE_Detail As cPE)
PE_Details.Add cPE_Detail ' ERROR: Object variable or With
' block variable not set
End Function
The module code that calls this is as follows:
调用这个的模块代码如下:
Dim clsPE As cPE ' Summary version of PE
Dim clsPE_Detail As cPE ' A detailed PE
Dim i as Integer
Set clsPE = New cPE ' This is the PE which will also contain a list of detailed PEs
' Add three instances of detailed cPE to the summary cPE object
for i = 1 to 3
Set clsPE_Detail = New cPE
clsPE_Detail.PE_ID = clsPE.PE_ID
clsPE_Detail.PE_ID_Index = clsPE.PE_ID_Index
'etc.
clsPE.AddPEDetail clsPE_Detail ' see above
next i
回答by Sorceri
In your cPE class add the method Class_Initialize and initialize your variables. As you have it now you never set PE_Details so it is null/nothing
在您的 cPE 类中添加方法 Class_Initialize 并初始化您的变量。正如你现在拥有的那样,你永远不会设置 PE_Details 所以它是空的/什么都没有
Private Sub Class_Initialize()
set PE_Details = New Collection
End Sub