Access/VBA Library

SortDictionary

Sorts a dictionary by it's keys.

Syntax

SortDictionary( aDictionary )
Parameters
Name Type Description
aDictionary Dictionary Required. Dictionary to be sorted.
Code
Public Sub SortDictionary(aDictionary As Dictionary)
    Dim idx As Long
    Dim tempArr()
    Dim newDict As Dictionary
    
    If aDictionary Is Nothing Then Exit Sub
    
    With aDictionary
        If aDictionary.Count <= 1 Then Exit Sub
        ' Create an array containing all keys
        ReDim tempArr(0 To .Count - 1)
    
        For idx = 0 To .Count - 1
            tempArr(idx) = .Keys(idx)
        Next idx
        
        ' Sort keys
        Call QuickSort(tempArr, LBound(tempArr), UBound(tempArr))
        ' Create new Dictionary and add in sort order
        Set newDict = New Dictionary
        
        For idx = LBound(tempArr) To UBound(tempArr)
            newDict.Add tempArr(idx), .Item(tempArr(idx))
        Next idx
    End With
    
    Set aDictionary = newDict
End Sub

Dictionarytag:Dictionary

See also

  • QuickSort