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

时间:2012-12-19 07:52:20

标签: vbscript

我正在寻找与字典对象项相关的解决方法

Dim a, d 'Create some variables

 Set d = CreateObject("Scripting.Dictionary")

 d.Add "a", "Athens" 'is possible I know 

 d.Add "a", "Athens","India","Paris" ' Is this Possible  under same Key?

说明快照:( 更新

  Manger ID            EMPID      EMPID     EMPID     EMPID ......

     11                12          10
     15                10 
     20                22          45        46
     40

如何使用字典对象实现上表?给我一些想法。

谢谢,

4 个答案:

答案 0 :(得分:4)

编辑:使变量名称更加友好

编辑:包含OP的reading

的Scripting.Dictionary参考
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的问题中的值读入字典并检索值

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

答案 1 :(得分:1)

没有。根据定义,字典数据类型使用必须唯一的键。我知道在大多数实现中都是这样的,但是我最接近VBscript的Scripting.Dictionary的权威参考是这个TechNet blurb

  

键是唯一的条目:单个Dictionary对象中没有两个键可以是相同的。

答案 2 :(得分:0)

这是另一个观看此问题并需要另一种方法来解决此问题的人的另一个例子。我觉得这可以有所帮助。

Dim objDictionary
Set objDictionary = CreateObject("Scripting.Dictionary")
    dicKey = 69
    dicValues = ""
    dicVal = "val1"
    dicVal2 = "val2"
    dicVal3 = "val3"
    objDictionary.add dicKey, DicValues1 & DicValues2
    chang = -1

if chang = -1 then  
    objDictionary.item(dicKey) = dicVal & "," & dicVal2
    chang = -69
end if

if chang = -69 then
    objDictionary.item(dicKey) = dicVal3 & ", " & dicVal & ", " & dicVal2
    chang = -1
end if

for each objDictionary_key in objDictionary.keys
    msgbox "Key: " & objDictionary_Key & " Value: " & objDictionary.item(objDictionary_Key)
next 

我希望这会有所帮助!

答案 3 :(得分:0)

如果您尝试在一个键中添加多个项目,则它们将是键的重复,并且Vb Script不允许这样做。 要了解有关字典对象的更多信息,请参考以下链接。 How To Use Dictionary Object