Results 1 to 4 of 4

Thread: Removing duplicates from a list box

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Oct 2006
    Posts
    91

    Removing duplicates from a list box

    i'm using this code to remove duplicates from a listbox

    VB Code:
    1. For i = List1.ListCount - 1 To 1 Step -1
    2.       If List1.List(i) = List1.List(i - 1) Then
    3.           List1.RemoveItem i
    4.         End If
    5. Next i
    and it works if the list's are small, but if i have over 1000 entries like i do normally, it doesnt remove duplicates.

    any idea?

  2. #2
    Hyperactive Member
    Join Date
    Aug 2003
    Location
    Wigan, UK
    Posts
    291

    Re: Removing duplicates from a list box

    That will only work if the listbox is sorted because you are always comparing the next item up and not any other item. For a fast way of deleting duplicates is to either check for the item before adding a new item to the listbox or use this
    VB Code:
    1. Option Explicit
    2. Private Declare Function SendMessageString Lib "user32" Alias "SendMessageA" _
    3. (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As String) As Long
    4. Const LB_FINDSTRINGEXACT = &H1A2
    5.  
    6. '--------------------------------------
    7.  
    8. For i = List1.ListCount - 1 To 0 Step -1
    9.   If SendMessageString(List1.hwnd, LB_FINDSTRINGEXACT, -1, ByVal List1.List(i)) <> i Then
    10.     List1.RemoveItem i
    11.    End If
    12.   Next i

  3. #3
    Oi, fat-rag! bushmobile's Avatar
    Join Date
    Mar 2004
    Location
    on the poop deck
    Posts
    5,592

    Re: Removing duplicates from a list box

    i posted this in your previous thread on removing duplicates from listboxes:
    VB Code:
    1. Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" ( _
    2.     ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
    3.  
    4. Private Const LB_FINDSTRINGEXACT = &H1A2
    5.  
    6. Private Sub Command1_Click()
    7.     Dim lPos As Long, N As Long
    8.  
    9.     Do While N < List1.ListCount
    10.         Do
    11.             lPos = SendMessage(List1.hwnd, LB_FINDSTRINGEXACT, N, ByVal List1.List(N))
    12.             If lPos > N Then List1.RemoveItem lPos
    13.         Loop While lPos > N
    14.         N = N + 1
    15.     Loop
    16. End Sub
    Edit: was untested - corrected it so it works

  4. #4

    Thread Starter
    Lively Member
    Join Date
    Oct 2006
    Posts
    91

    Re: Removing duplicates from a list box

    excellent, thank you so much

Posting Permissions

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



Click Here to Expand Forum to Full Width