VBA : 密钥对字典

VBA : key-pair dictionary

我选择后期绑定,因为我在使用早期绑定时出错。
而不是显示 3 个活动表名称,输出是这样的

Key: Value:

以前从未尝试过。谁能指出我正确的方向?

Sub LoopKeys()

Dim key As Variant
Dim country As Variant

country = Array("Kentucky", "California", "Ohio")

dic.Add "Kentucky", "Alicia"
dic.Add "California", "Ken"
dic.Add "Ohio", "Benjamin"

For sheet = LBound(country) To UBound(country)
ThisWorkbook.Worksheets(country(sheet)).Activate

    If ActiveSheet.Name = " & key & " Then
        Debug.Print "Key: " & key & " Value: " & dic(key)
    End If

Next

End Sub

在 Scripting.Dictionary 对象中,您需要遍历 Keys 集合:

Dim key As Variant
For Each key In dic.Keys
    Debug.Print "Key: " & key & " Value: " & dic(key)
Next key

更新 1:


Sub LoopKeys()
    Dim dic As Scripting.Dictionary
    Set dic = New Scripting.Dictionary

    Dim s As Worksheet
    For Each s In ThisWorkbook.Sheets
        dic.Add key:=CStr(s.Index), Item:=s.Name
    Next s

    Dim key As Variant
    For Each key In dic.Keys
        Debug.Print "Key: " & key & " Value: " & dic(key)
    Next key

    Set dic = Nothing
End Sub

'Key: 1 Value: Sheet1
'Key: 2 Value: Sheet2
'Key: 3 Value: Sheet3

更新二:


Sub LoopKeys()
    Dim dic As Scripting.Dictionary
    Set dic = New Scripting.Dictionary

    With dic
        .Add key:="Kentucky", Item:="Alicia"
        .Add key:="California", Item:="Ken"
        .Add key:="Ohio", Item:="Benjamin"
    End With

    Dim key As Variant
    For Each key In dic.Keys
        ThisWorkbook.Worksheets(key).Activate
        Debug.Print "Key: " & key & " Value: " & dic(key)
    Next key

    Set dic = Nothing
End Sub