Добавление комментариев к каждой строке:
Sub unique()
'Declare a collection object called `arr`. Despite the name, it's not an array. Also declare the variable `a` as type variant (default)
Dim arr As New Collection, a
'Declare an array of type variant, being used here in this example and it will be loaded with fruit names.
Dim aFirstArray() As Variant
'Declare a variable called `i` as a long integer type
Dim i As Long
'Here's are our example single-dimensional array for which we want to find unique values.
aFirstArray() = Array("Banana", "Apple", "Orange", "Tomato", "Apple", _
"Lemon", "Lime", "Lime", "Apple")
'If we encounter an error adding `aFirstArray` array elements/items into our `arr` collection object then ignore them
On Error Resume Next
'Loop through each element(fruit name) in the array `aFirstArray`
For Each a In aFirstArray
'Add the item to the collection. The key and the value are both being set to the fruitname which is now in variable `a`
'If the key (fruit name) already exists, that `On Error Resume Next` will ignore the error that pops.
arr.Add a, a
Next
'Now we have a collection object `arr` that contains unique values from the array held in both the key and value of each item.
'Iterate from 1 to the however many unique items are in the collection object `arr`
For i = 1 To arr.Count
'Print the value (fruitname) out to the workbook
Cells(i, 1) = arr(i)
Next
End Sub
Причина, по которой здесь используется объект collection
, заключается в том, что он работает во многом как массив, но вместо индекса, содержащего значение, мы можемустановить key
.Ключи должны быть уникальными, поэтому, когда мы пытаемся добавить тот же ключ ПОСЛЕ того, как он уже установлен с value
, он выдает ошибку.В итоге получается объект коллекции с уникальными ключами (и в данном случае совпадающими значениями) из массива.
Вы увидите похожие версии этой подпрограммы / функции, также используя объекты Dictionary.Я предпочитаю их коллекциям, так как объект словаря имеет метод exists
, поэтому вместо On Error Resume Next
, который является чем-то вроде костыля, вы можете проверить, существует ли key
в вашем словаре, прежде чем добавлятьIf Not myDictionary.Exists(keyvalue) Then myDictionary.Add keyValue, val
.