How do I sort a collection?

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

Does anyone know how to sort a collection in VBA?

9条回答
  •  一整个雨季
    2020-11-27 05:41

    If your collection doesn't contain objects and you only need to sort ascending, you might find this easier to understand:

    Sub Sort(ByVal C As Collection)
    Dim I As Long, J As Long
    For I = 1 To C.Count - 1
        For J = I + 1 To C.Count
            If C(I) > C(J) Then Swap C, I, J
        Next
    Next
    End Sub
    
    'Take good care that J > I
    Sub Swap(ByVal C As Collection, ByVal I As Long, ByVal J As Long)
    C.Add C(J), , , I
    C.Add C(I), , , J + 1
    C.Remove I
    C.Remove J
    End Sub
    

    I hacked this up in minutes, so this may not be the best bubble sort, but it should be easy to understand, and hence easy to modify for your own purposes.

提交回复
热议问题