从第18行开始的vba列表数组?

时间:2017-03-09 21:01:31

标签: excel vba

我有以下代码,列出了数组中的唯一值:

Sub LIST()
  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 = 18 To arr.Count
     Cells(i, 3) = arr(i)
  Next

End Sub

我想从第18行开始列出这些值,但是当我设置I = 18时,这并没有列出任何内容。请有人告诉我我哪里出错了吗?

2 个答案:

答案 0 :(得分:2)

您可以切换到Dictionary对象并利用其Keys属性:

Sub LIST()
    Dim aFirstArray() As Variant, a As Variant

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

    With CreateObject("Scripting.Dictionary")
        For Each a In aFirstArray
            .Item(a) = a
        Next
        Cells(18, 3).Resize(.Count) = Application.Transpose(.Keys)
    End With

End Sub

答案 1 :(得分:0)

或者删除重复项:

arr = Array("Banana", "Apple", "Orange", "Tomato", "Apple", "Lemon", "Lime", "Lime")
Set r = [C18].Resize(UBound(arr) + 1)
r = Application.Transpose(arr)
r.RemoveDuplicates 1