1

I'm familiar with using Dictionaries in VBA, but I wanted to try out a SortedList. I read through the msdn doc for it and thought it uses the same .Add structure as the Dictionary.

I've been struggling to actually populate the SortedList. I'm not sure how what I'm doing is any different from this answer from How to make a list in VBA (not a dictionary)?. I'd VTC my own question as Duplicate, but somehow it's not the same thing.

I'm using a simple list:

enter image description here

And this is the Code -

Option Explicit

Sub testing()

    Dim sortList As Object
    Dim dict As Object
    Set sortList = CreateObject("System.Collections.SortedList")
    Set dict = CreateObject("Scripting.Dictionary")
    Dim i As Long
    Dim key As Variant
    Dim item As Variant

    For i = 1 To 7
        key = Sheet1.Cells(i, 1)
        item = Sheet1.Cells(i, 2)
        dict.Add key, item
        sortList.Add key, item
    Next

End Sub

I even went the extra step (just in case) and made everything Variant as I know the SortedList wants Objects.

I can't seem to retrieve anything from the SortList

What am I missing?

I'm trying to retrieve it the way I'd retrieve a dictionary

For Each key In sortList.keys
    Sheet1.Cells(i, 6) = key
    Sheet1.Cells(i, 7) = sortList.item(key)
Next
Raystafarian
  • 2,902
  • 2
  • 29
  • 42

1 Answers1

0

I'm getting the keys and items the wrong way out of the SortedList

For i = 0 To sortList.Count - 1
    key = sortList.getkey(i)
    item = sortList.item(key)
    Sheet1.Cells(i + 1, 6) = key
    Sheet1.Cells(i + 1, 7) = item
Next

Different than in a Dictionary -

i = 1
For Each key In dict
    Sheet1.Cells(i, 6) = key
    Sheet1.Cells(i, 7) = dict(key)
    i = i + 1
Next
Raystafarian
  • 2,902
  • 2
  • 29
  • 42