vba 反转集合中的项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4203329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 12:18:38  来源:igfitidea点击:

Reversing the Items In a Collection

vbacollections

提问by Dan

What is the easiest way to reverse the items in a VBA collection?

反转 VBA 集合中项目的最简单方法是什么?

回答by Hans Olsson

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

回答by Regit

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

回答by Regit

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.

在起始集合上使用内置迭代器。要使用“添加,之前”,集合必须至少有 1 个成员,因此添加一个项目,然后在反向集合完成后将其删除。

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