按数字键排序字典

JSZ*_*JSZ 2 arrays excel vba dictionary excel-vba

我有一个带有整数键和整数项的字典,只需要根据键对字典进行排序,但我发现的所有例子都只适用于字符串键.

Tim*_*ams 7

将键作为数组抓取,对该数组进行排序,然后使用已排序的数组从字典中提取值.

Sub Tester()

    Dim d As Object
    Dim i As Long, arr, k

    Set d = CreateObject("scripting.dictionary")


    With d
        .Add 3, 33
        .Add 1, 33
        .Add 2, 55
        .Add 5, 77
    End With

    arr = d.keys  '<< get keys in an array

    ' "sort" through the array, and get the values from the dictionary
    Debug.Print "key", "value"
    For i = 0 To UBound(arr)
        k = Application.Small(arr, i + 1)
        Debug.Print k, d(k)
    Next i

End Sub
Run Code Online (Sandbox Code Playgroud)

输出:

  key          value
  1             33   
  2             55   
  3             33   
  5             77
Run Code Online (Sandbox Code Playgroud)