Reputation: 311
Say I have a class called Person, with a Name and an Age properties, and another collection called Family, with properties like Income, Address, and a collection of Persons inside it. I cannot find a full example on how to implement this concept. Furthermore, as I am new to both collections and classes, I am not succeeding also in making a small subroutine to use these two functions.
Here is my best try, based on the limited resources available on the internet:
' Inside the class Module Person .........................
Public pName As String
Public pAge As Integer
Public Property Get Name() As String
Name = pName
End Property
Public Property Let Name(value As String)
pName = value
End Property
' Inside the class Module Family .........................
' ... Income and address Properties are supposed
' ... declared and will not be used in this trial
Private colPersons As New Collection
Function AddP(aName As String, anAge As integer)
'create a new person and add to collection
Dim P As New Person
P.Name = aName
P.Age = anAge
colPersons.Add R ' ERROR! Variable colPersons not Defined!
End Function
Property Get Count() As Long
'return the number of people
Count = colPersons.Count
End Property
Property Get Item(NameOrNumber As Variant) As Person
'return this particular person
Set Item = Person(NameOrNumber)
End Property
And now the Subroutine that tries to use the above:
Sub CreateCollectionOfPersonsInsideAFamily()
'create a new collection of people
Dim Family_A As New Family
'add 3 people to it
Family_A.AddP "Joe", 13
Family_A.AddP "Tina", 33
Family_A.AddP "Jean", 43
'list out the people
Dim i As Integer
For i = 1 To Family_A.Count
Debug.Print Family_A.Item(i).Name
Next i
End Sub
Naturally this is giving errors: Variable Not defined (see above comment)
Upvotes: 2
Views: 60
Reputation: 311
Sorry for the inconvenience... But the problem was that the line:
Private colPersons As New Collection
should not be place after other properties have been declared (here not shown: Address and Income)
After placing this line in the declaration area at the top of its class, all the code has proved to be correct.
Upvotes: 2