VBA 字典删除项目

Sha*_*han 1 vba combobox dictionary

我正在尝试从字典中删除已经从组合框中选择的项目。我有以下代码,但我不知道问题是什么。它在 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
Run Code Online (Sandbox Code Playgroud)

gen*_*pos 6

这是在 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
Run Code Online (Sandbox Code Playgroud)

我建议您在添加/删除之前使用 If-Then 检查“Key”,以便您能够根据“错误的密钥”或“不存在的密钥”拦截错误