【问题标题】:Add Items to late-bound SortedList in VBA在 VBA 中将项目添加到后期绑定的 SortedList
【发布时间】:2018-05-21 05:00:44
【问题描述】:

我熟悉在 VBA 中使用字典,但我想尝试使用 SortedList。我通读了msdn doc 并认为它使用与字典相同的.Add 结构。

我一直在努力实际填充 SortedList。我不确定我在做什么与this answerHow to make a list in VBA (not a dictionary)? 有什么不同。 我将 VTC 我自己的问题作为重复,但不知何故它不是一回事。

我正在使用一个简单的列表:

这是代码 -

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

我什至采取了额外的步骤(以防万一)并制作了 Variant 的所有内容,因为我知道 SortedList 想要 Objects

我似乎无法从 SortList 中检索任何内容

我错过了什么?

我正在尝试以检索字典的方式检索它

For Each key In sortList.keys
    Sheet1.Cells(i, 6) = key
    Sheet1.Cells(i, 7) = sortList.item(key)
Next

【问题讨论】:

  • 不要使用监视列表来检查内容 - 它不会显示在那里...
  • 很公平,我确实尝试将它打印回来,这是它失败的地方,基本上告诉我没有钥匙。可能是我的打印方法不对,我会贴出来的。
  • 谢谢蒂姆,我觉得很可笑

标签: vba excel sortedlist


【解决方案1】:

我从 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

与字典中的不同 -

i = 1
For Each key In dict
    Sheet1.Cells(i, 6) = key
    Sheet1.Cells(i, 7) = dict(key)
    i = i + 1
Next

【讨论】:

  • For i = 0 To sortList.Count - 1 会更通用。
  • 你是绝对正确的。我一直讨厌For Each 带有字典的循环。
  • @Raystafarian 可以使用索引遍历字典,但必须使用早期绑定。
  • @AntiDrondert 您可以使用 Keys 索引遍历后期绑定字典。诀窍是访问字典的 Keys 数组。 Key = dict.Keys()(i)
  • @thomas 也告诉我消息!
猜你喜欢
  • 2014-08-25
  • 2012-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-20
相关资源
最近更新 更多