VBA学习笔记3-数据结构类型SortedList

在VBA中,虽然没有内置的SortedList数据类型,但可以通过使用Collection对象或自定义类来实现类似的功能。SortedList通常用于按键值对排序和检索数据。以下是一个示例,演示如何使用Collection对象来模拟SortedList的功能:

 

Sub SortedListExample()
    Dim sortedList As New Collection
    Dim key As String
    Dim value As String
    
    ' 添加键值对到SortedList
    sortedList.Add "apple", "A"
    sortedList.Add "banana", "B"
    sortedList.Add "orange", "O"
    
    ' 按键排序
    For Each key In SortCollection(sortedList)
        value = sortedList(key)
        Debug.Print key & ": " & value
    Next key
End Sub

Function SortCollection(col As Collection) As Variant
    Dim arr() As String
    Dim i As Integer
    
    ReDim arr(1 To col.Count)
    
    For i = 1 To col.Count
        arr(i) = col(i)
    Next i
    
    QuickSort arr, LBound(arr), UBound(arr)
    
    SortCollection = arr
End Function

Sub QuickSort(arr As Variant, left As Integer, right As Integer)
    Dim i As Integer, j As Integer
    Dim pivot As String, temp As String
    
    i = left
    j = right
    pivot = arr((left + right) \ 2)
    
    While i <= j
        While arr(i) < pivot
            i = i + 1
        Wend
        
        While arr(j) > pivot
            j = j - 1
        Wend
        
        If i <= j Then
            temp = arr(i)
            arr(i) = arr(j)
            arr(j) = temp
            i = i + 1
            j = j - 1
        End If
    Wend
    
    If left < j Then QuickSort arr, left, j
    If i < right Then QuickSort arr, i, right
End Sub

 

在上面的示例中,我们使用Collection对象模拟了一个SortedList,并实现了按键排序的功能。通过添加键值对到Collection中,并使用自定义的QuickSort函数对键进行排序,最终按照排序后的键顺序输出键值对。这个示例展示了SortedList的常见用途之一,即按键排序和检索数据。

希望这个示例对你有帮助!如果有任何问题或者需要进一步帮助,请随时告诉我。

posted @ 2022-12-07 20:49  vba是最好的语言  阅读(223)  评论(0)    收藏  举报