Remove Duplicates From A Listbox?
Hi,
Here's an example listbox:
Quote:
Hello World
Hi World
Hello World
How would I go about removing just one of the "Hello World" entries?
And this also needs to work with multiple duplicated text and without me specifying the duplicates.
Basically I need some code to check through a long listbox, find duplicates and remove them. (if there's 2 duplicates, remove 1, if theres 3 duplicates, remove 2 etc. etc.) I hope I've explained that enough for you to understand.
Re: Remove Duplicates From A Listbox?
Code:
Private Sub Command1_Click()
Dim i As Long
Dim 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 With
End Sub
Re: Remove Duplicates From A Listbox?
The best logic is to prevent the duplicates before they get added to the listbox.
Re: Remove Duplicates From A Listbox?
Quote:
Originally Posted by RobDog888
The best logic is to prevent the duplicates before they get added to the listbox.
Agreed. And, along those lines, this should do the trick.
Code:
Option Explicit
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
(ByVal hwnd As Long, _
ByVal wMsg As Long, _
ByVal wParam As Long, _
lParam As Any) As Long
Private Const LB_FINDSTRINGEXACT = &H1A2
Private Sub AddToListbox(strListBItem As String, LB As ListBox)
Dim lngListIndex As Long
' lngListIndex is the ListIndex if the item is found
lngListIndex = SendMessage(LB.hwnd, LB_FINDSTRINGEXACT, -1, ByVal strListBItem)
If lngListIndex = -1 Then
LB.AddItem strListBItem
Else
MsgBox strListBItem & " is already in the Listbox"
Exit Sub
End If
End Sub
Private Sub Command1_Click()
AddToListBox Text1.Text, List1
End Sub
Re: Remove Duplicates From A Listbox?
No thats not what I meant. If you are populating the listbox with duplicates then change your logic/code to filter and prevent the source from containing any duplictes at all. Like if its a query you can use the SELECT DISTINCT function in your sql depending upon the complexity of your query it will be as simply as that.
Re: Remove Duplicates From A Listbox?
vb Code:
Public Sub DeDupeList(ByVal List As ListBox)
On Error Resume Next
Dim lstCollection As New Collection
Dim i As Long
For i = 0 To List.ListCount - 1
lstCollection.Add List.List(i), List.List(i)
Next i
List.Clear
For i = 1 To lstCollection.Count
List.AddItem lstCollection.Item(i)
Next i
End Sub
Man am I gonna hear it for using On Error Resume Next :lol:
Re: Remove Duplicates From A Listbox?
Dont use "On Error Resume Next! Its bad programming practice!!!" :D
Re: Remove Duplicates From A Listbox?
Or just use Error Handling for "speed"...Collections are good...if you add a duplicate item (key) to a collection, you get an error.
But, for looping through it, Hack's method using API is the fastest I know of...