避免 Collection 中的重复值 [英] Avoid duplicate values in Collection
问题描述
我有以下值,我想将它们添加到集合中.如果值已在集合中,则消息应显示这已添加到您的集合中".
I have following values, and I want to add these to a collection. If the values are already in the collection, a message should show "this is already added in your collection".
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)
如何避免集合中的重复值?
How do I avoid duplicate values in a collection?
推荐答案
为了避免重复没有任何提示
使用这个方法.
To avoid duplicates without any prompts
use this method.
代码
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
屏幕截图
说明
集合是一组有序的项目,您可以将其称为一个单元.语法是
A collection is an ordered set of items that you can refer to as a unit. The syntax is
col.Add item, key, before, after
一个集合不能有两次相同的键,所以我们正在做的是使用我们正在添加的项目创建一个键.这将确保我们不会得到重复.On Error Resume Next
只是告诉代码忽略我们在尝试添加重复项时遇到的错误并简单地移动到下一个要添加的项目.CHR(34)
就是 "
所以上面的语句也可以写成
A collection cannot have the same key twice so what we are doing is creating a key using the item that we are adding. This will ensure that we will not get duplicates. The On Error Resume Next
is just telling the code to ignore the error we get when we try to add a duplicate and simply move on to the next item to add. The CHR(34)
is nothing but "
so the above statement can also be written as
col.Add 111, """" & 111 & """"
推荐阅读
HTH
这篇关于避免 Collection 中的重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!