使用ArrayList对字典键进行排序

时间:2017-10-17 22:44:19

标签: excel excel-vba vba

我似乎无法使用ArrayList对字典对象进行排序。代码有效,这意味着它返回Range("A1:A20")的唯一值列表。它只是没有对值进行排序。有任何想法吗?

Option Explicit

Public Sub Test()
    Dim wb As Workbook
    Set wb = ActiveWorkbook

    Dim ws As Worksheet
    Set ws = wb.ActiveSheet

    Dim rng As ListObject
    Set rng = ws.ListObjects(1)

    Dim arr() As Variant
    arr = Application.Transpose(rng.DataBodyRange.Value)

    Dim d As Scripting.Dictionary
    Set d = GetUnique(arr)

    Dim tempD As Scripting.Dictionary
    Set tempD = New Scripting.Dictionary

    Set tempD = SortDictionary(d)

    Dim key As Variant
    For Each key In d.Keys
        Debug.Print key, d.Item(key)
    Next key
End Sub

Private Function GetUnique(ByRef arr() As Variant) As Scripting.Dictionary
    Dim v As Variant
    Set GetUnique = New Scripting.Dictionary
    On Error Resume Next
    For Each v In arr
        GetUnique.Add v, v
    Next v
End Function

Private Function SortDictionary(dicObject As Scripting.Dictionary, Optional xlSortOrder As xlSortOrder = xlAscending) As Scripting.Dictionary
    Dim obj As Object
    Set obj = CreateObject("System.Collections.ArrayList")

    Dim v As Variant
    With obj
        For Each v In dicObject
            .Add v
        Next v
        .Sort
    End With

    Dim tempDic As Scripting.Dictionary
    Set tempDic = New Scripting.Dictionary

    Dim k As Variant
    For Each k In obj
        tempDic.Add k, dicObject(k)
    Next k

    Set SortDictionary = tempDic
End Function

1 个答案:

答案 0 :(得分:1)

那是因为当您将已排序的字典分配给tempD时,您指的是原始未排序的字典。尝试...

For Each key In tempD.Keys
    Debug.Print key, tempD.Item(key)
Next key

希望这有帮助!