Excel VBA:如何将项添加到类中的集合?

时间:2013-08-23 20:58:35

标签: class excel-vba vba excel

我有一个包含自身集合的类。 (顶级类包含集合中详细实例的摘要版本。)

目前该集合是一个公共变量,因为我还没有弄清楚使用私有变量的所有细节。我可以稍后解决。

如何向集合中添加项目?我因缺少对象变量而收到错误91.

感谢您之前的所有帮助。我一直在重新调整我的代码以更广泛地使用类,并且事情的清理真的很棒。

班级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

调用它的模块代码如下:

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

1 个答案:

答案 0 :(得分:8)

在cPE类中添加方法Class_Initialize并初始化变量。正如你现在所拥有的那样,你永远不会设置PE_Details,因此它是null / nothing

Private Sub Class_Initialize()
 set PE_Details = New Collection 
End Sub