Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

New column of unique names VBA

At the moment I have a range of names, and I need to create a new column which only contains the unique names.

Sub Unique_Values()

mySheet = Sheets("Sheet1").Range("E9:I20")

With CreateObject("scripting.dictionary")
For Each cell In mySheet
a = .Item(cell)
Next

Range("D2").Value = Join(.keys, vbLf)

End With
End Sub

This code creates a dictionary and returns the list of unique names, but it’s one long list (i’ve just inserted it into D2) but I need it to populate column D with the unique names, one name per cell. I can’t quite figure out how to loop through the keys and put them into an individual cell

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you use a collection you can create a unique list and write to the range. A collection will not let you add the same index key twice, therefore we ignore the error and then resume error checking when done writing.

Sub test()

    Dim myNames As New Collection
    Dim mySheet As Range
    Dim i As Long
    
    Set mySheet = Sheets("Sheet1").Range("E9:I20")
    
    On Error Resume Next
    For Each cell In mySheet
        myNames.Add cell, cell.Value
    Next
    On Error GoTo 0
    
    For i = 1 To myNames.Count
        Worksheets("Sheet1").Cells(i + 2, 4) = myNames(i)
    Next
    
End Sub
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading