How would I check if something is already in a ListBox?
Printable View
How would I check if something is already in a ListBox?
VB Code:
Private Sub cmdAdd_Click() For X = 0 To List1.ListCount - 1 If UCase(Trim(List1.List(X))) = UCase(Trim(Text1.Text)) Then MsgBox "Item Already Exists" Exit Sub End If Next List1.AddItem Text1.Text End Sub
This is the fastest way to prevent duplicates being inserted into a listbox...
VB Code:
Public Const LB_FINDSTRING = &H18F Public Const LB_ADDSTRING = &H180 Public Const CB_FINDSTRING = &H14C ' For a combobox Public Const CB_ADDSTRING = &H143 Public Declare Function SendMessageString Lib "user32" Alias "SendMessageA" _ (ByVal hwnd As Long, _ ByVal wMsg As Long, _ ByVal wParam As Long, _ ByVal lParam As String) As Long Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" _ (ByVal hwnd As Long, _ ByVal wMsg As Long, _ ByVal wParam As Long, _ lParam As Any) As Long Dim lngRetVal As Long lngRetVal = SendMessageString(MyListbox.hwnd, _ LB_FINDSTRING, -1&, _ strStringToBeAdded) ' lngRetVal is the ListIndex If lngRetVal > -1& Then ' It's in the list Else ' It's not in the list so add it Call SendMessage(MyListbox.hwnd, LB_ADDSTRING, 0, ByVal strStringToBeAdded) End If
Thanks, I had the same code eccept I was trying to use list1.index with Ubound (lol) instead of Listcount.