【问题标题】:Reversing the Items In a Collection反转集合中的项目
【发布时间】:2010-11-17 10:08:50
【问题描述】:

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

【问题讨论】:

标签: vba collections


【解决方案1】:

不知道有什么巧妙的方法,但你可以做类似的事情(代码未经测试):

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

【讨论】:

    【解决方案2】:

    从具有最大索引的成员开始逐步向下遍历起始集合。将每个成员添加到反向集合中。

    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
    

    【讨论】:

      【解决方案3】:

      在起始集合上使用内置迭代器。 要使用“添加,之前”,集合必须至少有 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-07-13
        • 1970-01-01
        • 1970-01-01
        • 2014-03-05
        • 1970-01-01
        • 1970-01-01
        • 2022-07-05
        相关资源
        最近更新 更多