VB and VBA Users Source Code: Enumerate a private collection in a class using For Each
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
VB/VBA Source Code
Enumerate a private collection in a class using For Each
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Thursday, June 29, 2000
Hits:
892
Category:
Visual Basic General
Article:
A collection class is often a good way to encapsulate the creation and maintenance of multiple instances of an object. Creating routines to add, find and delete members is relatively easy. Returning the count of objects is also easy. What is not obvious is how to let outside code use the For Each syntax on the collection contained in the class without making the internal collection public. It can be done as follows: Place the following code in a form: Private Sub Command1_Click() Dim oAlph As New clsAlphabet, Char as Variant 'Enumerate the private collection For Each Char In oAlph Debug.Print Char Next End Sub Place the following code in a class called clsAlphabet Option Explicit Private Alphabet As New Collection 'Private collection holding the letters of the alphabet 'NOTE: You must set the Procedure ID = -4 in the Procedure Attributes 'dialog (click 'Tools', 'Procedure Attributes' then 'Advanced') Public Property Get NewEnum() As IUnknown 'this property allows you to enumerate 'this collection with the For...Each syntax Set NewEnum = Alphabet.[_NewEnum] End Property 'Add the letters of the alphabet to the private collection Private Sub Class_Initialize() Dim iThisChar As Integer For iThisChar = 1 To 26 Alphabet.Add Chr(96 + iThisChar) Next End Sub While the code is visible in the code editor of VB click TOOLS, PROCEDURE ATTRIBUTES, ADVANCED. Make sure that NewEnum is selected in the NAME field and then enter -4 for the PROCEDURE ID. The value -4 is a special case that VB recognizes as providing enumeration data for the For Each syntax. You will now be able to perform a For Each enumeration over the private collection contained in your class (as shown above).
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder