|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
Sub RandomDictSort()
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
' 随机生成字典
dict.Add "key1", "value1"
dict.Add "key2", "value2"
dict.Add "key4", "value4"
dict.Add "key5", "value5"
dict.Add "key3", "value3"
' 打印原始字典
PrintDict dict
' 按键排序
SortDictByKey dict
PrintDict dict
' 按值排序
SortDictByValue dict
PrintDict dict
End Sub
' 打印字典
Sub PrintDict(dict As Object)
Dim key As Variant
For Each key In dict.keys
Debug.Print key & ": " & dict(key)
Next key
Debug.Print "----------------------"
End Sub
' 按键排序字典
Sub SortDictByKey(dict As Object)
Dim keys() As Variant
Dim key As Variant
Dim i As Long
' 获取字典的键
ReDim keys(0 To dict.Count - 1)
i = 0
For Each key In dict.keys
keys(i) = key
i = i + 1
Next key
' 排序键
BubbleSort keys
' 重新构建字典
Set dict = CreateObject("Scripting.Dictionary")
For i = LBound(keys) To UBound(keys)
dict.Add keys(i), "value" & Right$(keys(i), 1)
Next i
End Sub
' 按值排序字典
Sub SortDictByValue(dict As Object)
Dim keys() As Variant
Dim key As Variant
Dim i As Long
' 获取字典的键
ReDim keys(0 To dict.Count - 1)
i = 0
For Each key In dict.keys
keys(i) = key
i = i + 1
Next key
' 排序键
BubbleSortByValue dict, keys
' 重新构建字典
Set dict = CreateObject("Scripting.Dictionary")
For i = LBound(keys) To UBound(keys)
dict.Add keys(i), "value" & Right$(keys(i), 1)
Next i
End Sub
' 冒泡排序算法(按键排序)
Sub BubbleSort(arr() As Variant)
Dim i As Long
Dim j As Long
Dim temp As Variant
For i = LBound(arr) To UBound(arr) - 1
For j = i + 1 To UBound(arr)
If arr(i) > arr(j) Then
temp = arr(j)
arr(j) = arr(i)
arr(i) = temp
End If
Next j
Next i
End Sub
' 冒泡排序算法(按值排序)
Sub BubbleSortByValue(dict As Object, arr() As Variant)
Dim i As Long
Dim j As Long
Dim temp As Variant
For i = LBound(arr) To UBound(arr) - 1
For j = i + 1 To UBound(arr)
If dict(arr(i)) > dict(arr(j)) Then
temp = arr(j)
arr(j) = arr(i)
arr(i) = temp
End If
Next j
Next i
End Sub
|
|