FaruSZ
FaruSZ

Reputation: 61

Removes duplicates from listbox

I am trying to display items on a listbox, those items are duplicated in my worksheet, but when I want to show the listbox i want to show unique items, I tried to work with collections but it didnt help me. My code to populate my listbox is :

            Set ws = ActiveWorkbook.Worksheets(Personne)
            ActiveWorkbook.Worksheets(Personne).Activate

            fin_col_Form_Init = ws.Cells(6, 256).End(xlToLeft).Column
            UF_Profil_Edit1.ListBox_Form_Init.ColumnCount = 4
            UF_Profil_Edit1.ListBox_Form_Init.ColumnWidths = "300;100;100;100"

            For i = 2 To fin_col_Form_Init
                UF_Profil_Edit1.ListBox_Form_Init.AddItem ws.Cells(6, i)
                UF_Profil_Edit1.ListBox_Form_Init.List(UF_Profil_Edit1.ListBox_Form_Init.ListCount - 1, 1) = ws.Cells(7, i)
                UF_Profil_Edit1.ListBox_Form_Init.List(UF_Profil_Edit1.ListBox_Form_Init.ListCount - 1, 2) = ws.Cells(8, i)
                UF_Profil_Edit1.ListBox_Form_Init.List(UF_Profil_Edit1.ListBox_Form_Init.ListCount - 1, 3) = ws.Cells(9, i)
            Next i
        end if 
    Sample
end sub 

Where Sub is:

Sub Sample()
    RemovelstDuplicates ctrlListNames
End Sub

Where RemovelstDuplicates is:

 Public Sub RemovelstDuplicates(lst As msforms.ListBox)
    Dim i As Long, j As Long
    With lst
        For i = 0 To .ListCount - 1
            For j = .ListCount - 1 To (i + 1) Step -1
                If .List(j) = .List(i) Then
                    .RemoveItem j
                End If
            Next
        Next
    End With
End Sub

I got an error on the Sample code

Upvotes: 1

Views: 301

Answers (1)

FaruSZ
FaruSZ

Reputation: 61

I edited the code (changed the name of my listbox):

Sub Sample()
    RemovelstDuplicates ctrlListNames
End Sub

To

Sub Sample()
    RemovelstDuplicates UF_Profil_Edit1.ListBox_Form_Init
End Sub

And its working Thanks to all

Upvotes: 2

Related Questions