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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23511563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 03:00:59  来源:igfitidea点击:

Remove currently looped item from collection?

vbaexcel-vbaexcel

提问by user1283776

How do I remove the currently looped item from a collection? I get run-time error 13: Type mismatch on the line wls.Remove vl

如何从集合中删除当前循环的项目?我收到运行时错误 13: Type mismatch on the line 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

采纳答案by user1283776

Collection.Remove()method takes either key(if provided with the .Add()method) or index(by default) as parameter, so you can't provide an user-defined object as parameter to the Remove()method which explains the Type-mismatch error.

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

See a more on MSDN

MSDN上查看更多信息



You should really be using a Dictionarycollection if you are working with User Defined Types.

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



To achieve what you want use an iterator

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

dim i as long 
for i = Collection.Count to 1 step -1
    'Collection.Remove i
next i

回答by bobyuan

You must delete item while looping through the collection in backward order, otherwise it will cause error.

您必须在以倒序循环遍历集合时删除项目,否则会导致错误。

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

Why? Because Visual Basic collections are re-indexed automatically. If you try to delete in forward order, it will conflict with the outer loop and hence get the tricky error.

为什么?因为 Visual Basic 集合会自动重新索引。如果您尝试按正向顺序删除,它将与外部循环发生冲突,因此会出现棘手的错误。

Another example, to remove all items in the collection can be done like this:

另一个例子,要删除集合中的所有项目,可以这样做:

For i = 1 to col.Count
    col.Remove 1 'Always remove the first item.
Next i