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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Removing Objects from a Collection

Status
Not open for further replies.

RiceW

Programmer
Jan 31, 2003
8
US
Is there a way to remove objects from a collection without knowing the key? Or, is there a way to find the index of an object in a collection? Specifically, I want to check a property of an object in a collection. If it's false, I want to remove it, but I won't always know the key. Thanks in advance.
 
Sure but you'll have to loop through the collection:

Dim objTgt As Object

For Each objTgt In colObjects
With objTgt
If Not .MyProperty Then
.Remove
End If
End With
Next

Set objTgt = Nothing

Paul Bent
Northwind IT Systems
 
Oops, Remove isn't a property of your object. I can see how to do it by looping through twice. The first pass stores the index number of the objects in reverse order in an array. The second loop removes the objects indexed in the array.

Dim alngIndex() As Long
Dim lngC1 As Long
Dim lngC2 As Long

For lngC1 = colObjects.Count To 1 Step -1
If Not colObjects.Item(lngC1).MyProperty Then
Redim Preserve alngIndex(0 To lngC2)
alngIndex(lngC2) = lngC1
lngC2 = lngC2 + 1
End If
Next

If lngC2 > 0 Then
For lngC1 = LBound(alngIndex) To UBound(alngIndex)
colObjects.Remove alngIndex(lngC1)
Next
End If

Paul Bent
Northwind IT Systems
 
Or even in one loop:

For lngC1 = colObjects.Count To 1 Step -1
If Not colObjects.Item(lngC1).MyProperty Then
colObjects.Remove lngC1
End If
Next

Jeez, I've been working on a .chm file for the last 5 days and I'm definitely brain dead from the tedium :-(

Paul Bent
Northwind IT Systems
 
This is one of those times when ObjPtr actually comes in handy...

When adding the Objects to the collection, use the ObjPtr value of the object as the key, eg:
[tt]
colObjs.Add myObject, CStr(ObjPtr(myObject))
[/tt]
Once you've done that, a minor modification of paulbent's first code becomes viable:
[tt]
For Each objTgt In colObjects
With objTgt
If Not .MyProperty Then
colObjects.Remove CStr(ObjPtr(objTgt))
End If
End With
Next

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top