1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| Enabling For Each … Next
Along with robustness, you get For Each … Next back. Once again you can delegate all the work to the Collection object, by adding the following method:
' NewEnum must return the IUnknown interface of a
' collection's enumerator.
Public Function NewEnum() As IUnknown
Set NewEnum = mcolEmployees.[_NewEnum]
End Function
The important thing you're delegating to the Collection object is its enumerator. An enumerator is a small object that knows how to iterate through the items in a collection. You can't write an enumerator object with Visual Basic, but because the Employees class is based on a Collection object, you can return the Collection object's enumerator — which naturally enough knows how to enumerate the items the Collection object is holding.
The square brackets around the Collection object's _NewEnum method are necessary because of the leading underscore in the method name. This leading underscore is a convention indicating that the method is hidden in the type library. You can't name your method _NewEnum, but you can hide it in the type library and give it the procedure ID that For Each … Next requires.
To hide the NewEnum method and give it the necessary procedure ID
On the Tools menu, click Procedure Attributes to open the Procedure Attributes dialog box. In Name box, select the NewEnum method.
Click Advanced to show the advanced features. Check Hide this member to make NewEnum hidden in the type library.
In the Procedure ID box, type –4 (minus four) to give NewEnum the procedure ID required by For Each … Next. Click OK.
Important In order for your collection classes to work with For Each … Next, you must provide a hidden NewEnum method with the correct procedure ID. |