Good day. Is it possible to make friends the class I write (inside contains some collection / array) with the For Each loop, as is done in the Collection class? Example:

Dim example As New Collection example.Add 2 example.Add 3 Dim elem As Variant For Each elem In example Debug.Print elem Next elem 

It can be seen that in example, no function that returns a list of values ​​is explicitly called when a loop is passed to For Each. How can this behavior be implemented for any other type? As I understand it, the language itself uses some kind of service mechanism that implements the concept of an iterator.

    1 answer 1

    If your class contains a collection, then this can be done. Add a method (let the collection in the class be called mycollection )

     Public Property Get NewEnum() As IUnknown Set NewEnum = mycollection.[_NewEnum] End Property 

    Then export your class to a file, open it in a text editor and add the Attribute NewEnum.VB_UserMemId = -4 string to this method. In the end, it should look like this:

     Public Property Get NewEnum() As IUnknown Attribute NewEnum.VB_UserMemId = -4 Set NewEnum = mycollection.[_NewEnum] End Property 

    Import this class instead of yours and everything will work.

    Read more here https://stackoverflow.com/documentation/vba/5321/attributes#t=201608230625133754538

    • Correctly I understand that it’s already impossible to achieve such behavior for an array (or, as an example, for a user implementation of a binary tree)? - Roxio0
    • Unfortunately, I used only collections, so I’ll not say anything about arrays. Who else can that prompts. - Edward Izmalkov