我正在尝试从字典中删除已从组合框中选择的项目。我有以下代码,但我不知道问题是什么。它在d2给了我一个对象所需的错误(" v"& cbnr).Remove(ss)。
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
答案 0 :(得分:4)
这是在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检查“密钥”,这样您就可以根据“错误密钥”或“不存在密钥”来拦截错误