如何在不使用密钥的情况下从集合中删除值?

问题描述 投票:0回答:2

我在vba中有一个集合对象,我在其中添加了一堆ID值

Dim newCollection As New Collection 
newCollection.ADD Me.ID

有没有办法让我从集合中删除一个ID而不知道它存储的是哪个密钥?

我试着这样做:

newCollection.Remove """" & Me.ID & """" 

但我得到:

无效的过程调用或参数

ms-access access-vba
2个回答
2
投票

您需要(想要)添加“键”来查找值(它必须是一个字符串)。

以下代码显示了这是如何工作的:

Private Sub Command103_Click()

     Dim cValues    As New Collection

     cValues.Add 5, "5"
     cValues.Add 100, "100"
     cValues.Add 6, "6"

     cValues.Add Me.ID.Value, CStr(Me.ID.Value)


     cValues.Add 200, "200"

     GoSub displayList

    ' delete the 2 value based on index
    cValues.Remove (2)
    GoSub displayList

    ' remove a value by key
    cValues.Remove (CStr(Me.ID))

    GoSub displayList

    ' remove the 6 guy by KEY
     cValues.Remove ("6")

    GoSub displayList

    Exit Sub

displayList:

     Dim i       As Integer

     For i = 1 To cValues.Count
        Debug.Print i, "--->", cValues(i)
     Next i

     Return


End Sub

输出:

1            --->           5 
2            --->           100 
3            --->           6 
4            --->           15 
5            --->           200 


1            --->           5 
2            --->           6 
3            --->           15 
4            --->           200 

1            --->           5 
2            --->           6 
3            --->           200 


1            --->           5 
2            --->           200 

1
投票

在这种情况下,您尝试将Me.ID的内容作为字符串删除。您需要做的是确定您的ID的位置,然后将其删除。你可以这样做:

Dim newCollection As New Collection 
newCollection.ADD Me.ID

For I = 1 To newCollection.Count
    If newCollection.Item(I) = Me.ID Then
        newCollection.Remove I
        Exit For
    End If
Next I
© www.soinside.com 2019 - 2024. All rights reserved.