2015-11-14 151 views
0

我想从词典中删除已经从组合框中选择的项目。我有一个下面的代码,但我不知道问题是什么。它给了我一个对象在d2所需的错误(“v”& cbnr).Remove(ss)。VBA词典删除项目

a是一个数组。

Sub cb_pop2(cbnr As Integer) 
Dim i, j As Integer 
Dim d2 as object 
Dim ss as string  

Set d2 = CreateObject("Scripting.Dictionary") 
d2("v" & cbnr) = a 

For i = cbnr To 5 
UserForm1.Controls("ComboBox" & i).Clear 

    For j = cbnr To i 
     ss = UserForm1.Controls("ComboBox" & j - 1).Value 
     d2("v" & cbnr).Remove (ss) 
    Next j 
    UserForm1.Controls("ComboBox" & i).List = d2("v" & cbnr).keys 
    UserForm1.Controls("ComboBox" & i).ListIndex = 0 
Next i 

End Sub 
+3

这有点令人困惑。在'd2(“v”&cbnr)= a'处,你有一个名为'd2'的字典,其中有一条记录('d2.Count')。这个记录是''v“&cbnr'的* Key *和'a'的一个* Item * - (不知道** a **是什么)。唯一可以删除的是一个键/项目对,比如'd2.Remove(“v”&cbnr)'。所以你可以看到你不能从combox中删除键/项对,因为他们从来没有在字典中开始。 – Jeeped

+0

a是所有组合框的数组和列表源。 – Shan

回答

2

这是VBA

Sub TestDictionary() 
Set dict = CreateObject("Scripting.Dictionary") 
For x = 1 To 5 
    Key = "Start" & x 
    Value = 0 + x 
    If Not dict.Exists(Key) Then 
     dict.Add Key, Value 
    End If 
Next x 
For Each k In dict.keys 
    MsgBox (dict(k)) 
Next 
    If dict.Exists(Key) Then 
     dict.Remove Key 
    Else 
     'You can put here a code to show errors 
    End If 

End Sub 

使用字典的一个例子,我建议你使用一个IF-THEN到添加/删除所以前检查“键”,您将能够拦截取决于由错误“错误的钥匙”或“不存在的钥匙”