Remove Dupes in Listbox.-VBForums

# Thread: Remove Dupes in Listbox.

1. ## Remove Dupes in Listbox.

How do you remove the dupes in a listbox?

I tried doing it like this

VB Code:
`Dim Intx as integer for intx = 0 to list1.listcount - 1 if list1.list(intx) = list1.text thenlist1.removeitem(intx)end if next intx`

Thanks,
Sir Loin

2. ## Re: Remove Dupes in Listbox.

Nope. That will only remove what's in the textbox from the listbox. You'd be better off adding items to a second listbox, and then comparing each new item to all items in the second listbox to see if it should be deleted from the first listbox, or added to the second listbox.
It would be easier to just build the second listbox of unique items, then copy them back into the first listbox. That way you wouldn't have to delete anything from the first listbox.

3. ## Re: Remove Dupes in Listbox.

An easy way is to sort it (set Sorted to True). Then all duplicate items will be together (one after the other). Then you can use this code:

VB Code:
`Dim intItems As IntegerDim I As Integer intItems = List1.ListCount For I = intItems To 1 Step -1     If List1.List(I) = List1.List(I-1) Then          List1.RemoveItem (I)     End IfNext I`

4. ## Re: Remove Dupes in Listbox.

Originally Posted by baja_yu
An easy way is to sort it (set Sorted to True). Then all duplicate items will be together (one after the other). Then you can use this code:

VB Code:
`Dim intItems As IntegerDim I As Integer intItems = List1.ListCount For I = intItems To 1 Step -1     If List1.List(I) = List1.List(I-1) Then          List1.RemoveItem (I)     End IfNext I`
Cleaver, Thank You!

5. ## Re: Remove Dupes in Listbox.

Or, if they are not sorted and together, you can do
vb Code:
`Private Sub Command1_Click()Dim i As LongDim j As Long    With List1        For i = 0 To .ListCount - 1            For j = .ListCount To (i + 1) Step -1                If .List(j) = .List(i) Then                    .RemoveItem j                End If            Next        Next    End WithEnd Sub`

6. ## Re: Remove Dupes in Listbox.

How are you adding items to the ListBox? The best method of removing duplicates is not letting them get in there in the first place...otherwise, any of the above codes work. I have always done it as Hack posted

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

Featured