with Classes

A collection class is a VBA class that defines a Private Collection object and implements methods to add, remove, retrieve and count objects in the collections.


Built-in Collection Class

The problem with the built-in collection class is that you have no control over what gets added to that collection if your collection property is public in your class
The solution is to create a class that "wraps up" your collection and then provide methods and properties to emulate the Add, Remove and Item methods.
However you will loose the default Item method as well as the ability to perform a for-each loop
Instead of the For-Each-Next loop you must use Count and For-Next instead.



Custom Collection Class

To control what type of objects are placed into a collection, you must create a collection class.
Using a class gives you the ability to create custom replacements for the standard Add, Remove and Item methods.


It is possible to include the collection inside the actual class itself.
The advantage of adding the collection to the class means that you get much more control and you can prevent direct access to the collection from outside.
The disadvantage of adding the collection is that you cannot use the built-in Add, Count, Item and Remove methods and must write your own.
If you want to prevent direct access to the collection and create a certain amount of abstraction then you could add the Collection to the class itself.


Private colEmployees As New Collection 

Public Function Add(oEmployee As class_Employee)
   Call colEmployees.Add(Item:=oEmployee, Key:=oEmployee.Name)
End Function

Public Sub Remove(vItem As Variant)
   colEmployees.Remove vItem
End Sub

Public Property Get Item(vItem As Variant) As class_Employee
   Set Item = colEmployees(vItem)
End Property

Public Property Get Count() As Long
   Count = colEmployees.Count
End Property



© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext