开发者

Reversing the Items In a Collection

What is the easiest way to reverse the items in a VBA coll开发者_开发技巧ection?


Don't know of any neat way of doing it but you could do something like (code not tested):

Dim MyNewCol as New Collection
For Each obj in MyCol
    If MyNewCol.Count > 0 Then
        MyNewCol.Add item := obj, before := 1
    Else
        MyNewCol.Add item := obj
    End If
Next


Steps down through the starting collection beginning from the member with the largest index. Adds each member to the reversed collection.

Sub ReverseCollection(aCollection)

    Dim ndx As Integer
    Dim max As Integer
    Dim reversedCollection As New Collection
    max = aCollection.Count + 1

    For ndx = 1 To aCollection.Count
        reversedCollection.Add aCollection(max - ndx)
    Next ndx
End Sub


Uses the built-in iterator over the starting collection. To use 'Add, Before', the collection must have at least 1 member, so add an item and then remove it after the reversed collection is finished.

Sub ReverseCollection2(aCollection)

   Dim item As Variant
   Dim reversedCollection As New Collection
   reversedCollection.Add "dummy entry"
   For Each item In aCollection
       reversedCollection.Add item, Before:=1
   Next item
   reversedCollection.Remove reversedCollection.Count
End Sub
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜