Page tree

Welcome to FreeSoftwareServers Confluence Wiki

Skip to end of metadata
Go to start of metadata


Sub CreatePersonsCollectionSafer()
 Dim Persons As New clsPersons

 Persons.Add "RitaJ", "Smith"
 Persons.Add "SueB", "Jones"
 Persons.Add "Bob", "Brown"
 Dim Person As clsPersons
 Dim PersonNumber As Integer
 Debug.Print Persons.Count
 For PersonNumber = 1 To Persons.Count
  Debug.Print Persons.Item(PersonNumber).FullName
 Next PersonNumber
 Dim LastName As String
 LastName = "Brown"
 Debug.Print "Last Name = " & LastName & " & First Name = " & Persons.ItemByLastName(LastName).FirstName
End Sub

Class (clsPersons):

Option Explicit
Public Persons As New Collection
Private PersonsIndexDic As Object
Public FirstName As String
Public LastName As String
Private Sub Class_Initialize()
 Set PersonsIndexDic = CreateObject("scripting.dictionary")
End Sub

Sub Add(FirstName As String, LastName As String)
 Dim p As New clsPersons
 p.FirstName = FirstName
 p.LastName = LastName

 Persons.Add p
 PersonsIndexDic.Add Key:=LastName, Item:=PersonsIndexDic.Count + 1

End Sub

Sub Remove(NameOrNumber As Variant)
 Persons.Remove NameOrNumber
End Sub

Property Get Count() As Long
 Count = Persons.Count
End Property

Property Get Item(Index As Variant) As clsPersons
 Set Item = Persons(Index)
End Property

Property Get FullName() As String
 FullName = FirstName & " " & LastName
End Property

Property Get Items() As Collection
 Set Items = Persons
End Property

Property Get ItemByLastName(LastName As String) As clsPersons
   Set ItemByLastName = Persons(PersonsIndexDic(LastName))
End Property



  • No labels