我想将项目列表添加到集合中并避免添加重复项。这是我在 A 列中的列表
Apple
Orange
Pear
Orange
Orange
Apple
Carrot
Run Code Online (Sandbox Code Playgroud)
我只想添加
Apple
Orange
Pear
Carrot
Run Code Online (Sandbox Code Playgroud)
这是我想出的方法,它有效,但并不漂亮。
dim coll as New Collection
ln = Cells(Rows.Count, 1).End(xlUp).Row
coll.Add (Cells(1, 1).Value) 'Add first item manually to get it started
For i = 1 To ln
addItem = True 'Assume it's going to be added until proven otherwise
For j = 1 To coll.Count 'Loop through the collection
'If we ever find the item in the collection
If InStr(1, Cells(i, 1), coll(j), vbTextCompare) > 0 Then
addItem = False 'set this bool false
End If
Next j
If addItem = True Then 'It never got set to false, so add it
coll.Add (Cells(i, "A").Value)
End If
Next i
Run Code Online (Sandbox Code Playgroud)
有没有更简单的方法来做到这一点?最好是类似的东西
If Not coll.Contains(someValue) Then
coll.Add (someValue)
End If
Run Code Online (Sandbox Code Playgroud)
我强烈建议使用字典,因为它们具有许多集合所没有的功能,包括Exists函数。
话虽如此,创建一个函数会非常容易,该函数首先检查集合中是否存在值,然后创建另一个函数,仅在值不存在时添加该值。
要查看它是否已经存在,只需使用一个简单的 for 循环即可。如果该值存在,则返回 true 并退出该函数。
' Check to see if a value is in a collection.
' Functional approcah to mimic dicitonary `exists` method.
Public Function CollectionValueExists(ByRef target As Collection, value As Variant) As Boolean
Dim index As Long
For index = 1 To target.Count
If target(index) = value Then
CollectionValueExists = True
Exit For
End If
Next index
End Function
Run Code Online (Sandbox Code Playgroud)
使用新函数CollectionValueExists就像if条件语句一样简单,看看是否应该添加它。
为了使这一过程更加动态,您还可以使用 aParamArray来允许通过一次调用添加多个值。只需循环每个值并查看是否需要添加它。这不适用于您的示例,但可以灵活用于其他用途。
' Adds unique values to a collection.
' @note this mutates the origianal collection.
Public Function CollectionAddUnique(ByRef target As Collection, ParamArray values() As Variant) As Boolean
Dim index As Long
For index = LBound(values) To UBound(values)
If Not CollectionValueExists(target, values(index)) Then
CollectionAddUnique = True
target.Add values(index)
End If
Next index
End Function
Run Code Online (Sandbox Code Playgroud)
将它们放在一起,您可以简单地循环范围并调用新函数。
Private Sub demoAddingUniqueValuesToCollection()
Dim fruits As Collection
Set fruits = New Collection
Dim cell As Range
For Each cell In Range("A1", Range("A" & Rows.Count).End(xlUp))
CollectionAddUnique fruits, cell.value
Next cell
End Sub
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24998 次 |
| 最近记录: |