编辑添加了输出 X 和 Y 数组的解决方案
您可以使用SortedList 对象并构建一个辅助子,如下所示:
Sub SortDictionary(dict As Object)
Dim i As Long
Dim key As Variant
With CreateObject("System.Collections.SortedList")
For Each key In dict
.Add key, dict(key)
Next
dict.RemoveAll
For i = 0 To .Keys.Count - 1
dict.Add .GetKey(i), .Item(.GetKey(i))
Next
End With
End Sub
被利用如下:
SortDictionary dict '<--| give 'SortDictionary()' sub a dictionary object to sort by its keys
例如,这是一个测试:
Sub main()
Dim dict As Object
Dim key As Variant
Set dict = CreateObject("Scripting.Dictionary")
With dict
.Add 5, 15
.Add 4, 14
.Add 3, 13
.Add 2, 12
.Add 1, 11
End With
SortDictionary dict
With dict
For Each key In .Keys
Debug.Print key, .Item(key)
Next
End With
End Sub
上面的内容可以很容易地从字典keys和items中返回X和Y数组,如下所示:
Sub SortDictionaryToArray(dict As Object, XArray As Variant, YArray As Variant)
Dim i As Long
Dim key As Variant
With CreateObject("System.Collections.SortedList")
For Each key In dict
.Add key, dict(key)
Next
ReDim XArray(0 To .Count)
ReDim YArray(0 To .Count)
For i = 0 To .Keys.Count - 1
XArray(i) = .GetKey(i)
YArray(i) = .Item(.GetKey(i))
Next
End With
End Sub
在你的主子中被利用如下:
SortDictionaryToArray dict, Xs, Ys
正如您在这个完整的测试中看到的那样:
Sub main()
Dim dict As Object
Dim i As Long
Dim Xs As Variant, Ys As Variant
Set dict = CreateObject("Scripting.Dictionary")
With dict
.Add 5, 15
.Add 4, 14
.Add 3, 13
.Add 2, 12
.Add 1, 11
End With
SortDictionaryToArray dict, Xs, Ys
For i = 0 To UBound(Xs)
Debug.Print Xs(i), Ys(i)
Next
End Sub