Shari W
Shari W

Reputation: 537

Excel VBA: How do I add an item to a collection within a class?

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.

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

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

Upvotes: 3

Views: 8942

Answers (1)

Sorceri
Sorceri

Reputation: 8033

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

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

Upvotes: 9

Related Questions