从集合中删除当前循环的项目?

use*_*776 4 excel vba excel-vba

如何从集合中删除当前循环的项目?我收到运行时错误13:在行wls.Remove vl上键入不匹配

Sub FocusOnH(ByRef vls As Collection)
    Dim vl As CVegetableLine
    For Each vl In vls
        If vl.hValue <> 0 Then
            vl.volume = vl.hValue
        Else
            vls.Remove vl
        End If
    Next vl
End Sub
Run Code Online (Sandbox Code Playgroud)

bob*_*uan 6

在以向后顺序遍历集合时,必须删除项目,否则会导致错误。

Sub TestRemoveItemInCollection()
    Dim col As Collection, i As Integer
    Set col = New Collection
    col.Add "item1"
    col.Add "item2"
    col.Add "item3"
    col.Add "item4"

    ' Never use: For i=1 to col.Count
    For i = col.Count To 1 Step -1
        col.Remove i
    Next i

    Set col = Nothing
End Sub
Run Code Online (Sandbox Code Playgroud)

为什么?因为Visual Basic集合会自动重新索引。如果尝试以向前的顺序删除,它将与外部循环冲突,因此会遇到棘手的错误。

另一个示例,删除集合中的所有项目可以像这样完成:

For i = 1 to col.Count
    col.Remove 1 'Always remove the first item.
Next i
Run Code Online (Sandbox Code Playgroud)


小智 5

Collection.Remove()方法采用key(如果与.Add()方法一起提供)或index默认情况下)作为参数,因此您不能提供用户定义的对象作为Remove()解释类型不匹配错误的方法的参数。

MSDN上查看更多信息


Dictionary如果您正在使用用户定义类型,您真的应该使用集合。


要实现您想要的使用迭代器

dim i as long 
for i = Collection.Count to 1 step -1
    'Collection.Remove i
next i
Run Code Online (Sandbox Code Playgroud)