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

Excel VBA code to populate combobox with unique values does not work with number

I am using the following code to populate ComboBox on a userform in vba with unique values. I use the same code to populate two other ComboBoxes and it works fine. It doesn’t work when the data in the column is a number. In the same column, if I change the number to a text then it works. How can I get it to work with numbers also?

Sub uniqueYear()
    
Dim myCollection As Collection

On Error Resume Next
Set myCollection = New Collection

    With Me.cbxYear
        .Clear
        For Each cell In Sheets("Sheet1").range("AC2:AC" & Cells(Rows.Count, 1).End(xlUp).Row)
        If Len(cell) <> 0 Then
            Err.Clear
            myCollection.Add cell.Value, cell.Value
            If Err.Number = 0 Then .AddItem cell.Value
            End If
        Next cell
    End With
    
End Sub

>Solution :

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

I’d extract the job of collecting unique values to a separate method:

Sub uniqueYear()
    
    Dim myCollection As Collection, v, ws As Worksheet
    
    Set ws = ThisWorkbook.Worksheets("Sheet1") 'activeworkbook?
    
    Set myCollection = UniqueCollection(ws.Range("A2:A" & ws.Cells(Rows.Count, 1).End(xlUp).Row))

    With Me.cbxYear
        .Clear
        For Each v In myCollection
            .AddItem v
        Next v
    End With
End Sub

Function UniqueCollection(rng As Range) As Collection
    Dim c As Range, col As New Collection, v
    On Error Resume Next
    For Each c In rng.Cells
        v = c.Value
        If Not IsError(v) Then
            If Len(v) > 0 Then col.Add v, CStr(v) 'Key needs to be a String
        End If
    Next c
    On Error GoTo 0
    Set UniqueCollection = col
End Function
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