How do I sort a collection?

后端 未结 9 2060
臣服心动
臣服心动 2020-11-27 05:03

Does anyone know how to sort a collection in VBA?

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 06:01

    This code snippet works well, but it is in java.

    To translate it you could do it like this:

     Function CollectionSort(ByRef oCollection As Collection) As Long
    Dim smTempItem1 As SeriesManager, smTempItem2 As SeriesManager
    Dim i As Integer, j As Integer
    i = 1
    j = 1
    
    On Error GoTo ErrFailed
    Dim swapped As Boolean
    swapped = True
    Do While (swapped)
        swapped = False
        j = j + 1
    
        For i = 1 To oCollection.Count - 1 - j
            Set smTempItem1 = oCollection.Item(i)
            Set smTempItem2 = oCollection.Item(i + 1)
    
            If smTempItem1.Diff > smTempItem2.Diff Then
                oCollection.Add smTempItem2, , i
                oCollection.Add smTempItem1, , i + 1
    
                oCollection.Remove i + 1
                oCollection.Remove i + 2
    
                swapped = True
            End If
        Next
    Loop
    Exit Function
    
    ErrFailed:
         Debug.Print "Error with CollectionSort: " & Err.Description
         CollectionSort = Err.Number
         On Error GoTo 0
    End Function
    

    SeriesManager is just a class that stores the difference between two values. It can really be any number value you want to sort on. This by default sorts in ascending order.

    I had difficulty sorting a collection in vba without making a custom class.

提交回复
热议问题