-2

我找到了这段代码,但我很难理解它。你能详细解释一下吗?

https://stackoverflow.com/questions/3017852/vba-get-unique-values-from-array?answertab=active# =

    Sub unique() 
  Dim arr As New Collection, a 
  Dim aFirstArray() As Variant 
  Dim i As Long 

  aFirstArray() = Array("Banana", "Apple", "Orange", "Tomato", "Apple", _ 
  "Lemon", "Lime", "Lime", "Apple") 

  On Error Resume Next 
  For Each a In aFirstArray 
     arr.Add a, a 
  Next 

  For i = 1 To arr.Count 
     Cells(i, 1) = arr(i) 
  Next 

End Sub 
4

2 回答 2

1

为每一行添加注释:

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

于 2019-04-26T14:19:36.427 回答
0

aFirstArray() = ...创建一个值不是(不一定)唯一的数组。

下一个代码块尝试将这些项目中的每一个添加到 aCollection中,并使用On Error Resume Next来忽略如果您尝试将已经存在的项目添加到集合中会引发的错误,从而确保arr(Collection) 仅包含数组中的唯一值。

从方法上的Collection.Adddox

如果指定的键与集合的现有成员的键重复,也会发生错误。

于 2019-04-26T14:19:39.740 回答