lukeweatherstone
lukeweatherstone

Reputation: 45

Populating Combobox with Unique Values

I'm looking to populate a combobox with only unique text values from a column. If a value in the column is empty (i.e. "") then it takes the value from the adjacent column to the left (still making sure it's not a duplicate).

I've embedded a Public Sub within the Userform module to add the items without duplicates:

Public Sub addIfUnique(CB As ComboBox, value As String)

If CB.ListCount = 0 Then GoTo doAdd
    Dim i As Integer
    For i = 0 To CB.ListCount - 1
        If CB.List(i) = value Then Exit Sub
    Next
    doAdd:
        CB.AddItem value

End Sub

However when I try to call the sub, it tells me an object is required. What I've got so far is as follows:

Worksheets("Scrapers").Activate
Range("M9").Activate

Dim intX As Integer
Dim value As String

push_lt_cbo.Clear

Do Until ActiveCell.Offset(0, -1).value = 0
    If ActiveCell.value = "" Then
        value = ActiveCell.Offset(0, -1).Text
        Call addIfUnique((push_lt_cbo), (value))
    Else
        value = ActiveCell.Text
        Call addIfUnique((CB), (value))
    End If
Loop

Any help would be much appreciated!

LW

Upvotes: 2

Views: 8449

Answers (1)

ray
ray

Reputation: 8699

You're close:

Option Explicit 'Add this if you don't already have it

Private Sub UserForm_Initialize()
    Worksheets("Scrapers").Activate
    Range("M9").Activate

    Dim intX As Integer
    Dim value As String

    push_lt_cbo.Clear


    'Your loop will never end like this:
    'Do Until ActiveCell.Offset(0, -1).value = 0

    'Instead use a variable:
    Dim rowOffset As Integer
    rowOffset = 0
    Do Until ActiveCell.Offset(rowOffset, -1).value = 0
        'There was a lot of extra stuff here.  Simplifying:
        value = ActiveCell.Offset(rowOffset, -1).value

        'Remove optional CALL keyword.
        'Also remove paranthesis; they caused the error:
        addIfUnique push_lt_cbo, value

        'increment offset:
        rowOffset = rowOffset + 1
    Loop
End Sub
'Use 'msforms.ComboBox' to clarify.
Public Sub addIfUnique(CB As msforms.ComboBox, value As String)

If CB.ListCount = 0 Then GoTo doAdd
    Dim i As Integer
    For i = 0 To CB.ListCount - 1
        If CB.List(i) = value Then Exit Sub
    Next
doAdd:
        CB.AddItem value

End Sub

Upvotes: 1

Related Questions