且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

字典对象可以在同一个键下有多个项目吗?

更新时间:2022-12-20 19:56:59

使变量名称更易于操作

Makes variable name more OPfriendly

包括 OP 的 Scripting.Dictionary 参考 阅读

Include a Scripting.Dictionary Reference for OP's reading

Sub t()
    Dim d
    Dim a
    a = Array("Athens", "India", "Paris")
    Set d = CreateObject("Scripting.Dictionary")
    d.Add "a", a
    MsgBox Join(d.Item("a"), ",")
End Sub

将 OP 问题中的值读入字典并检索值

to read values as in OP's question into dictionary and retrieve the values

Sub t()
    Dim d As Object
    Dim values
    Dim height As Long
    Dim item
    Dim width As Long
    Dim i As Long, j As Long
    Dim MANGERID
    Dim EMPIDs
    Dim EMPID
    With ActiveSheet
        height = .Cells(.Rows.Count, 1).End(xlUp).Row
        If height < 2 Then
            Exit Sub
        End If
        Set d = CreateObject("Scripting.Dictionary")
        For i = 2 To height
            width = .Cells(i, .Columns.Count).End(xlToLeft).Column
            if width > 1 then  'make sure have EMPID
                ReDim values(1 To width - 1)
                Key = .Cells(i, 1).Value
                For j = 2 To width
                    values(j - 1) = .Cells(i, j).Value
                Next j
                d.Add Key, values
            end if
        Next i

        'displaying back the items in the dictionary
        For Each MANGERID In d.keys
            'value array
            EMPIDs = d.item(MANGERID)
            If TypeName(EMPIDs) = "Variant()" Then
                For Each EMPID In EMPIDs
                    Debug.Print MANGERID & ":" & EMPID
                Next EMPID
            End If
        Next MANGERID

        Set d = Nothing
    End With
End Sub