2012-12-19 55 views
4

我一個人找相關字典的解決方法對象項目字典對象可以在同一個鍵下有多個項目嗎?

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 

如何上表中,然後可以使用Dictionary對象來實現?給我一些想法。

謝謝,

回答

3

編輯:使變量名更OPfriendly

編輯:包括OP的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 

編輯的Scripting.Dictionary參考:讀值作爲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 
+0

你能爲我的更新描述編碼嗎? –

+0

你的意思是你的「描述快照:」部分是輸入excel部分,你想將它們存儲在字典中? – Larry

+0

是的,拉里!你是對的!還希望看到如何訪問這些項目,一旦所有的鍵和項都加載到Dictionary對象中! –

1

否。根據定義,字典數據類型使用的鍵必須是唯一的。我知道是這樣的大多數實現,但我可以來爲VBScript的Scripting.Dictionary的權威參考最接近的是這樣的TechNet blurb

的關鍵是一個唯一的入口:一個Dictionary對象中沒有兩個鍵就可以一樣。

+0

我在找如果相同的鍵可以包含多個值或不是? –

+1

我想在這種情況下,你會有一個字典的數組。 –

+0

我更新了主題描述,你可以看一看嗎?並給我建議。 –

0

這是另一個例子,對於任何其他誰查看這一點,需要另一個r解決方案。我覺得這可以有所幫助。

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 

我希望這有助於一些!

相關問題