How do I sort a collection?

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

Does anyone know how to sort a collection in VBA?

9条回答
  •  猫巷女王i
    2020-11-27 06:07

    This is my implementation of BubbleSort:

    Public Function BubbleSort(ByRef colInput As Collection, _
                                        Optional asc = True) As Collection
    
        Dim temp                    As Variant
        Dim counterA                As Long
        Dim counterB                As Long
    
        For counterA = 1 To colInput.Count - 1
            For counterB = counterA + 1 To colInput.Count
                Select Case asc
                Case True:
                    If colInput(counterA) > colInput(counterB) Then
                        temp = colInput(counterB)
                        colInput.Remove counterB
                        colInput.Add temp, temp, counterA
                    End If
    
                Case False:
                    If colInput(counterA) < colInput(counterB) Then
                        temp = colInput(counterB)
                        colInput.Remove counterB
                        colInput.Add temp, temp, counterA
                    End If
                End Select
            Next counterB
        Next counterA
    
        Set BubbleSort = colInput
    
    End Function
    
    Public Sub TestMe()
    
        Dim myCollection    As New Collection
        Dim element         As Variant
    
        myCollection.Add "2342"
        myCollection.Add "vityata"
        myCollection.Add "na"
        myCollection.Add "baba"
        myCollection.Add "ti"
        myCollection.Add "hvarchiloto"
        myCollection.Add "stackoveflow"
        myCollection.Add "beta"
        myCollection.Add "zuzana"
        myCollection.Add "zuzan"
        myCollection.Add "2z"
        myCollection.Add "alpha"
    
        Set myCollection = BubbleSort(myCollection)
    
        For Each element In myCollection
            Debug.Print element
        Next element
    
        Debug.Print "--------------------"
    
        Set myCollection = BubbleSort(myCollection, False)
    
        For Each element In myCollection
            Debug.Print element
        Next element
    
    End Sub
    

    It takes the collection by reference, thus it can easily return it as a function and it has an optional parameter for Ascending and Descending sorting. The sorting returns this in the immediate window:

    2342
    2z
    alpha
    baba
    beta
    hvarchiloto
    na
    stackoveflow
    ti
    vityata
    zuzan
    zuzana
    --------------------
    zuzana
    zuzan
    vityata
    ti
    stackoveflow
    na
    hvarchiloto
    beta
    baba
    alpha
    2z
    2342
    

提交回复
热议问题