Search code examples
excelvbalistboxuserform

ListBox without duplicates


I have two ListBoxes on a UserForm. The first ListBox is linked to a table. The goal is after double clicking an item, the value is inserted in the second ListBox.

I tried to prevent duplicates from appearing in the second ListBox, so you couldn't accidentally insert the same item twice.

Private Sub listbox_variante_DblClick(ByVal Cancel As MSForms.ReturnBoolean)

Dim x As Integer

For x = 0 To listbox_variante.ListCount - 1
    If listbox_variante.Selected(x) = True Then
        listbox_seleccion.AddItem (listbox_variante.List(x))
    End If
Next x

End Sub


Private Sub UserForm_Initialize()
listbox_variante.RowSource = "Tabla2[DESCRIPCIÓN]"
End Sub

How can I prevent duplicate items being added from Listbox_variante to Listbox_seleccion?


Solution

  • I haven't tested it, but try...

    Private Sub listbox_variante_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
    
        Dim x As Long
        Dim y As Long
        Dim bFound As Boolean
        
        bFound = False
        For x = 0 To listbox_variante.ListCount - 1
            If listbox_variante.Selected(x) = True Then
                For y = 0 To listbox_seleccion.ListCount - 1
                    If listbox_seleccion.List(y) = listbox_variante.List(x) Then
                        Beep 'optional
                        bFound = True
                        Exit For
                    End If
                Next y
                If Not bFound Then
                    listbox_seleccion.AddItem listbox_variante.List(x)
                Else
                    bFound = False
                End If
            End If
        Next x
    
    End Sub