28 April 2022 17:30
excel - Sort Dictionary Keys using ArrayList - Stack Overflow
by cascamortoOption 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
(1 marks)