There are two basic bits of code on the internet for ensuring your listbox does not add a duplicate item to it.
- One of the ways is to loop through ever single list item and compare each of the list items to the item you want to add. If you get through the entire list without a match you know you have no duplicate so the item gets added to the listbox.
DOWNSIDE: slow, especially if your list has thousands of items.
- The second way is setting the .text of the listbox to whatever the text is you want to add. For example if you want to add “a big fury cat”, set list1.text = “a big fury cat” and then check the listindex property. If it is -1 then the item is not in the list and you can add it.
DOWNSIDE: does not work if the .multiselect is either 1- Simple or 2 – Extended. Only works if the listbox .multiselect property is 0 – none.
The ideal way to add non duplicate list items to list box and the fastest way
Top of your module:
Declare Function SendMessageByString Lib "user32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As String) As Long
Public Const LB_FINDSTRINGEXACT = &H1A2
The function that adds non