Populate unique values into a VBA array from Excel

2020-01-23 13:00发布

Can anyone give me VBA code that will take a range (row or column) from an Excel sheet and populate a list/array with the unique values, i.e.:

table
table
chair
table
stool
stool
stool
chair

when the macro runs would create an array some thing like:

fur[0]=table
fur[1]=chair
fur[2]=stool

8条回答
萌系小妹纸
2楼-- · 2020-01-23 13:21

In this situation I always use code like this (just make sure delimeter you've chosen is not a part of search range)

Dim tmp As String
Dim arr() As String

If Not Selection Is Nothing Then
   For Each cell In Selection
      If (cell <> "") And (InStr(tmp, cell) = 0) Then
        tmp = tmp & cell & "|"
      End If
   Next cell
End If

If Len(tmp) > 0 Then tmp = Left(tmp, Len(tmp) - 1)

arr = Split(tmp, "|")
查看更多
放荡不羁爱自由
3楼-- · 2020-01-23 13:30

Combining the Dictionary approach from Tim with the variant array from Jean_Francois below.

The array you want is in objDict.keys

enter image description here

Sub A_Unique_B()
Dim X
Dim objDict As Object
Dim lngRow As Long

Set objDict = CreateObject("Scripting.Dictionary")
X = Application.Transpose(Range([a1], Cells(Rows.Count, "A").End(xlUp)))

For lngRow = 1 To UBound(X, 1)
    objDict(X(lngRow)) = 1
Next
Range("B1:B" & objDict.Count) = Application.Transpose(objDict.keys)
End Sub
查看更多
登录 后发表回答