收集列中的所有名称并将它们放入Excel中的数组中

时间:2011-07-21 11:17:10

标签: arrays excel vba excel-vba

我有一张带有数据表的excel工作表。该表的一列包含公司名称。例如,"Apple""Microsoft""Asus"。该列可能包含重复的公司名称。

如何在包含此列的 distinct 成员的VBA中填充数组?

1 个答案:

答案 0 :(得分:4)

您可以使用不允许重复使用相同密钥的vba collection

Option Explicit

Sub UniqueList()
  Dim i As Long
  Dim rList As Range
  Dim cUnique As New Collection
  Dim aFinal() As String

  'change the range depending on the size of your title (or use a named range)
  Set rList = Range("A1:M1")

  'Loop over every column and add the value to the collection (with unique key)
  For i = 1 To rList.Columns.Count
      On Error Resume Next
      cUnique.Add rList(1, i), CStr(rList(1, i))
  Next i

  'Store back the value from the collection to an array
  ReDim aFinal(1 To cUnique.Count, 1 To 1)
  For i = 1 To cUnique.Count
      aFinal(i, 1) = cUnique(i)
  Next i

  'Use aFinal to do whatever you want
End Sub