I am trying to sort a dictionary with a function that I found online by an object property which is the Id but on this For Each i In dict
line I am getting this error message Microsoft VBScript runtime error: Object doesn't support this property or method. I have tried For Each i In dict.Items
but I get the same error message with 'dict.Items' I am using a older version of VBScript so it does not have features like dict.Count
VBScript Class:
Class TestClass
Public ID
Public TestText
Private Sub Class_Initialize
TestText = ""
End Sub
End Class
Set gDic = CreateObject("Scripting.Dictionary")
For i = 1 to 5
Set temp = new TestClass
temp.ID = i
temp.TestText = "Test" & i
gDic.Add i,temp
Next
Set NewDic = SortDict(gDic)
msgbox NewDic.Items()(1).TestText
Sort function:
Function SortDict(ByVal dict)
Dim i, j, temp
For Each i In dict
For Each j In dict
If(dict.Item(i) <= dict.Item(j)) Then
temp = dict.Item(i)
dict.Item(i) = dict.Item(j)
dict.Item(j) = temp
End If
Next
Next
Set SortDict = dict
End Function
Try modifying your function to:
Before Sorting:
After Sorting:
I could not find a better way to swap the values. I am sure there is a better way to do that. Will update it once I get something.
If you need to do a single pass along the dictionary you could use a disconnected recordset to sort the keys, then retrieve the values from the dictionary in the order to get the keys from the recordset.
To add onto the answers provided by @Potato, I needed to sort by descending two values in a dictionary and compare these values to a database. Luckily the UI allowed me to first sort by descending and then I used the Sorting method provided by @Potato to compare the values to the DB. I would have had to use more dictionaries if I were required to sort more than one value in the DB.
This function takes a dictionary a groups it by similar values such as ID. Then sorts that dictionary by a second value in ReverseSortDescDict(descDict)
This function sorts by descending before comparing. Included print statements to see dictionary object.