Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting a Collection of Objects

Status
Not open for further replies.

RSfromCO

Programmer
May 3, 2002
149
US
I have a custom object A_Object, that contains a Vba.Collection of another custom object B_Object.

If I am trying to display a list of information from the collection of B_Objects, I can just step through the collection, such as...

Dim obj As B_Object
For Each obj In A_Object.B_Objects
'do something...
Next obj

This all works great if I just step through the collection and pluck out the data items, HOWEVER, I want to display information on my form based upon sorting the collection of B_Objects first by one or two data fields.

Is there a good way to sort a collection of objects using one or more of the data elements for those objects?

My collections are small (0 to 5 items), so using the most efficient algorithm is not important. I would prefer something easily understood over something really efficient.

I can't find very clear documentation on the Vba.Collection methods. I am not sure if the .Add method always adds an item to the end of the collection. Is there a way to 'insert' an item into a collection at a certain index? If I can insert items at a specified index then it should be easy to create a new collection and just insert the items where they should go into the new collection.
 
RSfromCO,
By default the item is added the the end of the collection, but there is an optional Before and After argument that will allow you to add the new item, er, um before or after another item.
Syntax
[tt]object.Add item, key, before, after[/tt]

With that said you could do an inner loop that compares the item you are about to add to the exising items in the collection to determine where to add the new item.

Hope this helps,
CMP

(GMT-07:00) Mountain Time (US & Canada)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top