在VBA中检索字典的第n个键

4

在VBA中,是否可以提取字典中的第n个键及其值?类似于:

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

我尝试将单元格(Lastrow +i)的值赋为字典diccompare(UBound(RecSource) - Counter + i)中键的值。


2
不,不是在VBA中,而是在任何语言中都不可能。字典中的键没有编号。请参见此处的第2个答案 - https://dev59.com/4HI-5IYBdhLWcg3whIik - Vityata
1
啊,好的,谢谢你提供链接。那我会另想办法解决问题。 - Vlad M
通常情况下,如果您想比较字典的键,则这不是一个好主意 - 字典保证每个键都是唯一的。 - Vityata
2个回答

6
不确定我是否完全理解您的意思,类似于这样。
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)) - Nathan_Sav

3

你可以使用这个辅助函数

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接