jammerules
New Member
- Joined
- Nov 16, 2009
- Messages
- 13
- Office Version
- 365
- Platform
- Windows
I am trying to sort a VBA dictionary with the following keys and values. It is sorting the keys alphabetically. What I want is for it to treat the keys as "MMM-DD" format and sort. Is it possible? How do I make array list convert the keys to a date format (MMM-DD)?
This is the code
May-1 12
Jan-21 14
Dec-6 11
Feb-24 15
This is the code
VBA Code:
Sub TestSortByKey()
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
dict.Add "May-1", 12
dict.Add "Jan-21", 14
dict.Add "Dec-6", 11
dict.Add "Feb-24", 15
' Sort Ascending
Set dict = SortDictionaryByKey(dict)
PrintDictionary "Key Ascending", dict
End Sub
Public Function SortDictionaryByKey(dict As Object, Optional sortorder As XlSortOrder = xlAscending) As Object
Dim arrList As Object
Dim key As Variant, coll As New Collection
Dim dictNew As Object
Set arrList = CreateObject("System.Collections.ArrayList")
For Each key In dict
arrList.Add key
Next key
arrList.Sort
If sortorder = xlDescending Then
arrList.Reverse
End If
Set dictNew = CreateObject("Scripting.Dictionary")
For Each key In arrList
dictNew.Add key, dict(key)
Next key
Set arrList = Nothing
Set dict = Nothing
Set SortDictionaryByKey = dictNew
End Function
Public Sub PrintDictionary(ByVal sText As String, dict As Object)
Debug.Print vbCrLf & sText & vbCrLf & String(Len(sText), "=")
Dim key As Variant
For Each key In dict.Keys
Debug.Print key, dict(key)
Next
End Sub