VBA:密钥对字典

圣诞老人

我选择了后期绑定,因为我在使用早期绑定时遇到了错误。
而不是显示 3 activesheet 名称,输出是这样的

核心价值:

以前从未尝试过这个。任何人都可以指出我正确的方向吗?

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
科斯塔斯 K。

在 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

更新 2:


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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章