避免在Collection中重复值

use*_*292 11 vb6 vba

我有以下值,我想将它们添加到集合中.如果值已在集合中,则应显示一条消息"此内容已添加到您的集合中".

Dim OrdLines As New Collection

OrdLines.Add (111,this is first item)

OrdLines.Add (222,this is second item)

OrdLines.Add (333,this is third item)

OrdLines.Add (444,this is fourth item)
Run Code Online (Sandbox Code Playgroud)

如何避免集合中的重复值?

Sid*_*out 13

为避免重复,请without any prompts使用此方法.

Sub Sample()
    Dim col As New Collection
    Dim itm

    On Error Resume Next
    col.Add 111, Cstr(111)
    col.Add 222, Cstr(222)
    col.Add 111, Cstr(111)
    col.Add 111, Cstr(111)
    col.Add 333, Cstr(333)
    col.Add 111, Cstr(111)
    col.Add 444, Cstr(444)
    col.Add 555, Cstr(555)
    On Error GoTo 0

    For Each itm In col
        Debug.Print itm
    Next
End Sub
Run Code Online (Sandbox Code Playgroud)

截图

在此输入图像描述

说明

集合是一组有序的项目,您可以将其称为一个单元.语法是

col.Add item, key, before, after
Run Code Online (Sandbox Code Playgroud)

集合不能具有两次相同的密钥,因此我们正在做的是使用我们添加的项创建密钥.这将确保我们不会重复.这On Error Resume Next只是告诉代码忽略我们在尝试添加副本时所获得的错误,只需转到下一个要添加的项目即可.这CHR(34)只是"所以上面的陈述也可以写成

col.Add 111, """" & 111 & """"
Run Code Online (Sandbox Code Playgroud)

建议阅读

Visual Basic集合对象

HTH


Bob*_*b77 6

这是Dictionary提供一些优点的场景之一.

Option Explicit

'Requires a reference to Microsoft Scripting Runtime.

Private Sub Main()
    Dim Dict As Scripting.Dictionary 'As New XXX adds overhead.
    Dim Item As Variant

    Set Dict = New Scripting.Dictionary
    With Dict
        .Item(111) = 111
        .Item(222) = 222
        .Item(111) = 111
        .Item(111) = 111
        .Item(333) = 333
        .Item(111) = 111
        .Item(222) = 222
        .Item(333) = 333

        For Each Item In .Items
            Debug.Print Item
        Next
    End With
End Sub
Run Code Online (Sandbox Code Playgroud)