How can I check if the listbox has the specified item?
Printable View
How can I check if the listbox has the specified item?
VB Code:
Dim i As Long With List1 For i = 0 To .ListCount - 1 If Text1.Text = .List(i) Then MsgBox "Item already exists in List" 'if it is already there, boogie Exit Sub End If Next 'if it is not present, add it .AddItem Text1.Text End With
Why not Dim i as integer? Are you sure?
I'm positive. I always use longs (well, almost always.)Quote:
Originally Posted by vb6_
thanks
A listbox is limited to 32K items, so an Integer is sufficient. You can also use the SendMessage API to search without looping. Here is an example that I have to search a listbox and a combobox. If it beeps, the item is found, if not, it is added.
VB Code:
Option Explicit Private 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 Private Const CB_FINDSTRINGEXACT = &H158 Private Const LB_FINDSTRINGEXACT = &H1A2 Public newitem As String Sub searchcombo() Dim lngRetVal As Long lngRetVal = SendMessageString(Combo1.hWnd, _ CB_FINDSTRINGEXACT, -1&, _ newitem) If lngRetVal <> -1& Then Beep ' It's already in the list and lngRetVal is the listindex Else Combo1.AddItem newitem End If End Sub Private Sub Form_Load() Dim x As Integer Combo1.AddItem "test" Combo1.AddItem "dog" Combo1.AddItem "cat" newitem = "frog" For x = 0 To 5 List1.AddItem Chr$(34) & x & Chr$(34) List1.ItemData(x) = 0 Next x searchcombo newitem = "7" searchlist End Sub Sub searchlist() Dim lngRetVal As Long lngRetVal = SendMessageString(List1.hWnd, _ LB_FINDSTRINGEXACT, lngRetVal&, _ newitem) If lngRetVal <> -1& Then Beep ' It's already in the list and lngRetVal is the listindex Else List1.AddItem Chr$(34) & newitem & Chr$(34) End If End Sub