[RESOLVED] For Each with custom collection class
If I have created a custom collection class which encapsulates a standard Collection object, how then can I enumerate its members by using For Each?
e.g.
VB Code:
Dim objWindow As CWindow ' Custom class
Dim objWindows As CWindows ' Custom collection class
objWindows.GetWindows ' Populate the collection
' Now how can I provide support for this:
For Each objWindow In objWindows
' ....
Next objWindow
I think it works with a NewEnum method or something, but they are all hidden. Any ideas?
Re: For Each with custom collection class
The code for NewEnum to enable For...Each statements on a collection is
VB Code:
Public Property Get NewEnum() As IUnknown
Set NewEnum = [I]Name of Collection Variable[/I].[_NewEnum]
End Property
You must also set the Procedure Attribute for this property. Just copying and pasting the above code will not work.
Open the Class module
Tools -> Procedure Attributes menu
In the Name: combobox select NewEnum
Click the Advanced button
In the Procedure Id ComboBox type in -4
Optionally check Hide This Member.
If you open the class module in Notepad you should see something like
VB Code:
Public Property Get NewEnum() As IUnknown
Attribute NewEnum.VB_UserMemId = -4
Attribute NewEnum.VB_MemberFlags = "40"
Set NewEnum = Name of Collection variable.[_NewEnum]
End Property
Re: For Each with custom collection class
Re: [RESOLVED] For Each with custom collection class
Just out of interest, what if I didn't have a collection variable and was instead doing it manually. Does the NewEnum method return the next item in the collection each time it is called? If so, what does it return when you run out of items?
Re: [RESOLVED] For Each with custom collection class
Quote:
what if I didn't have a collection variable and was instead doing it manually.
For...Each works on arrays as well. Not sure I understand what you mean by "doing it manually".
Quote:
Does the NewEnum method return the next item in the collection each time it is called?
Yes.
Quote:
If so, what does it return when you run out of items?
The For...Each loop just exits. You would need the code the "Compiler" generates to figure out how it implements For...Each. As to what it returns, most likely Null or Nothing.
Re: [RESOLVED] For Each with custom collection class
I found a page on it. Thanks for your help :)