Title | Create a custom collection that supports For Each |
Keywords | custom collection, For Each, enumerate, enumerator, NewEnum |
Categories | Software Engineering |
|
|
Give the custom collection a private (normal) collection where it can store objects. Create Add, Remove, and other methods that you want to provide.
|
|
Private m_Employees As Collection
' Add an Employee object to the collection.
Public Sub Add(ByVal emp As Employee, Optional ByVal key As _
Variant)
If IsMissing(key) Then
m_Employees.Add emp
Else
m_Employees.Add emp, key
End If
End Sub
' Return the number of items in the collection.
Public Function Count() As Long
Count = m_Employees.Count
End Function
' Remove an Employee object from the collection.
Public Sub Remove(ByVal Index As Variant)
m_Employees.Remove Index
End Sub
' Return an Employee object.
Public Function Item(ByVal Index As Variant) As Employee
Set Item = m_Employees(Index)
End Function
|
|
To make Item the collection's default method (so you can say "my_collection(key_value)" as you can with a normal collection):
- Select Tools\Procedure Attributes
- Select this function in the Name dropdown.
- Click Advanced.
- Select (Default) in the Procedure ID dropdown.
To allow For Each enumeration, create the following NewEnum function. In this example, m_Employees is the name of the custom collection's private (normal) Collection object.
|
|
Public Function NewEnum() As IUnknown
Set NewEnum = m_Employees.[_NewEnum]
End Function
|
|
Next do the following:
- Open the collection class in the code designer.
- Select Tools\Procedure Attributes.
- Select this function in the Name dropdown.
- Click Advanced.
- Enter -4 as the Procedure ID.
Now the program can use For Each on the collection as in:
|
|
Private Sub ListEmployees()
Dim emp As Employee
Dim txt As String
For Each emp In m_Employees
txt = txt & emp.LastName & ", " & _
emp.FirstName & vbCrLf
Next emp
txtEmployees.Text = txt
End Sub
|
|
|
|