开发者

Collect all names in a column and put them in an Array in Excel

开发者_高级运维

I have an excel worksheet with a table of data. One column of the table contains the names of companies. For example, "Apple", "Microsoft", "Asus". The column may contain duplicate company names.

How can I populate an array in VBA which contains the distinct members of this column?


You can use a vba collection which does not allow duplicates for the same key:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜