Make a new column without duplicates VBA?

后端 未结 4 1164
无人及你
无人及你 2021-01-07 08:18

I have a column of cells whose values are something like this:

a
a
b
b
c
c
c
c
d
e
f
f

etc.

I\'m looking to take the non-duplicate

4条回答
  •  日久生厌
    2021-01-07 08:45

    I use a collection, which can't have duplicate keys, to get the unique items from a list. Try to add each item to a collection and ignore the errors when there's a duplicate key. Then you'll have a collection with a subset of unique values

    Sub MakeUnique()
    
        Dim vaData As Variant
        Dim colUnique As Collection
        Dim aOutput() As Variant
        Dim i As Long
    
        'Put the data in an array
        vaData = Sheet1.Range("A1:A12").Value
    
        'Create a new collection
        Set colUnique = New Collection
    
        'Loop through the data
        For i = LBound(vaData, 1) To UBound(vaData, 1)
            'Collections can't have duplicate keys, so try to
            'add each item to the collection ignoring errors.
            'Only unique items will be added
            On Error Resume Next
                colUnique.Add vaData(i, 1), CStr(vaData(i, 1))
            On Error GoTo 0
        Next i
    
        'size an array to write out to the sheet
        ReDim aOutput(1 To colUnique.Count, 1 To 1)
    
        'Loop through the collection and fill the output array
        For i = 1 To colUnique.Count
            aOutput(i, 1) = colUnique.Item(i)
        Next i
    
        'Write the unique values to column B
        Sheet1.Range("B1").Resize(UBound(aOutput, 1), UBound(aOutput, 2)).Value = aOutput
    
    End Sub
    

提交回复
热议问题