避免在Collection中重复值

时间:2013-09-14 07:53:44

标签: vba vb6

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

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)

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

4 个答案:

答案 0 :(得分:11)

为避免重复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

<强>截图

enter image description here

<强>解释

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

col.Add item, key, before, after

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

col.Add 111, """" & 111 & """"

建议阅读

The Visual Basic Collection Object

HTH

答案 1 :(得分:6)

这是“词典”提供一些优势的场景之一。

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

答案 2 :(得分:-1)

使用Add方法和密钥。

语法:

OrderLines.Add(ObjectToAdd, Key)

记住key是一个字符串。

示例:

OrdLines.Add(222,"222")
OrdLines.Add(222,"333")
OrdLines.Add(222,"444")

OrdLines.Add(222,"222") 'This will give error

答案 3 :(得分:-1)

built in method that allows you check for duplicates,假设您 总是分配Key值。这优先于On Error Resume Next

If Not OrdLines.Contains(key_value) Then
    OrdLines.Add(item_value, key_value, before, after)
End If

注意这是VB.NET,而不是VBA / VB6。在VBA / VB6中,您可以编写类似于the approach given, here的自定义函数。

相关问题