【问题标题】:Retrieve nth key in dictionary VBA检索字典 VBA 中的第 n 个键
【发布时间】:2017-03-24 15:14:00
【问题描述】:

是否可以从字典中提取第 n 个键及其在 VBA 中的值?像

For i = 1 To Counter + diccompare.Count - UBound(RecSource)
WS.Cells(Lastrow + i, "A") = diccompare.Keys(UBound(RecSource) - Counter + i)
Next

我试图为 Cell(Lastrow +i) 分配字典 diccompare(UBound(RecSource) - Counter + i) 中键的值的地方

【问题讨论】:

  • 没有。不是在 VBA 中,但在任何语言中都是不可能的。字典中的键没有编号。请参阅此处的 2. 答案 - stackoverflow.com/questions/1820506/…
  • 嗯,好的,谢谢你的链接。然后我会以其他方式找到解决方法
  • 一般来说 - 如果你想比较字典的键,这不是一个好主意 - 字典保证每个键都是唯一的。

标签: vba excel dictionary


【解决方案1】:

不确定我是否完全理解你,像这样

Sub KeyTest()

Dim d As New Scripting.Dictionary

d.Add "Test1", 1
d.Add "Test2", 2
d.Add "Test3", 99

Debug.Print d.Keys()(1)

End Sub

【讨论】:

  • @VladM 查看您的问题,因为.Keys() 返回一个数组,您可以跳过循环并使用这些行Range("a1").Resize(UBound(d.Keys()) + 1, 1).Value = (Application.Transpose(d.Keys))
【解决方案2】:

你可以使用这个helper功能:

Function GetNthKey(dict As Dictionary, nth As Long)
    Dim arr As Variant
    With dict
        arr = .Keys
        GetNthKey = arr(nth - 1)
    End With
End Function

在你的“主要”代码中被利用如下:

Dim diccompare As Dictionary 

Set diccompare = New Dictionary

With diccompare
    .Add 1, "a"
    .Add 2, "b"
    .Add 3, "c"
    .Add 4, "d"
End With

MsgBox GetNthKey(diccompare, 2) '<--| returns "2", i.e. the 2nd key

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-28
    相关资源
    最近更新 更多