5

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

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

4 回答 4

4

编辑:使变量名更易于操作

编辑:包括 Scripting.Dictionary Reference 以供 OP阅读

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
于 2012-12-19T08:35:34.760 回答
1

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

键是唯一的条目:单个 Dictionary 对象中的两个键不能相同。

于 2012-12-19T07:56:28.797 回答
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 

我希望这会有所帮助!

于 2016-06-02T16:33:19.707 回答
0

如果您尝试在一个键中添加多个项目,则它们将是键的重复,而 Vb 脚本不允许这样做。要了解有关字典对象的更多信息,请参阅以下链接。 如何使用字典对象

于 2019-02-09T17:55:33.160 回答