读取一个excel列,并将其唯一值放入一个数组中

我有一个不同的值的列。 我必须从列中只select唯一的值,并放入一个数组中。

我正在使用下面的代码相同,但它将另一列而不是数组中的唯一值。

Sub GetUniqueSections() Dim d As Object, c As Variant, i As Long, lastRow As Long Dim a(8) As String Dim j Set d = CreateObject("Scripting.Dictionary") lastRow = Cells(Rows.Count, 1).End(xlUp).Row c = Range("C2:C" & lastRow) For i = 1 To UBound(c, 1) d(c(i, 1)) = 1 Next i Range("R2").Resize(d.Count) = Application.Transpose(d.Keys) End Sub 

在下面的代码中, UniqueValueArrayFromRange使用与Scripting.Dictionary相同的技术replace您的GetUniqueSections 。 你可以用你需要的任何东西来代替"A1:A14" ,输出数组将会在arr

 Option Explicit Sub Test() Dim rng As Range Dim arr As Variant Dim i As Integer ' pass range values to function for unique values Set rng = Sheet1.Range("A1:A14") arr = UniqueValueArrayFromRange(rng) ' test return values For i = LBound(arr) To UBound(arr) Debug.Print arr(i) Next i End Sub Function UniqueValueArrayFromRange(ByRef rngSource As Range) As Variant Dim dic As Object Dim rngCell As Range ' create dictionary and only add new values Set dic = CreateObject("Scripting.Dictionary") For Each rngCell In rngSource If Not dic.Exists(rngCell.Value) Then dic.Add rngCell.Value, 1 End If Next rngCell ' return key collection as array UniqueValueArrayFromRange = dic.Keys End Function