views:

197

answers:

3

This request is based in MS Access VBA. I would like to know what the most efficient way is, to see if an item exists in a listbox control.

+1  A: 

Unfortunately there is no more efficient way than a linear search, unless you know that your listbox is sorted or indexed in some particular fashion.

For i = 1 To TheComboBoxControl.ListCount
  if TheComboBoxControl.ItemData(i) = "Item to search for" Then do_something()
Next i
Sparr
+1  A: 

If you don't mind resorting to the Windows API you can search for a string like this:

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

Dim index as Integer
Dim searchString as String
searchString = "Target" & Chr(0)

index = SendMessage(ListBox1.hWnd, LB_FINDSTRINGEXACT , -1, searchString)

Which should return the index of the row that contains the target string.

Rik Garner
+2  A: 

Here is a sample function that might be adapted to suit.

Function CheckForItem(strItem, ListB As ListBox) As Boolean
Dim rs As DAO.Recordset
Dim db As Database
Dim tdf As TableDef

    Set db = CurrentDb

    CheckForItem = False

    Select Case ListB.RowSourceType
        Case "Value List"
            CheckForItem = InStr(ListB.RowSource, strItem) > 0

        Case "Table/Query"
            Set rs = db.OpenRecordset(ListB.RowSource)

            For i = 0 To rs.Fields.Count - 1
                strList = strList & " & "","" & " & rs.Fields(i).Name
            Next

            rs.FindFirst "Instr(" & Mid(strList, 10) & ",'" & strItem & "')>0"

            If Not rs.EOF Then CheckForItem = True

        Case "Field List"

            Set tdf = db.TableDefs(ListB.RowSource)

            For Each itm In tdf.Fields
                If itm.Name = strItem Then CheckForItem = True
            Next

    End Select

End Function
Remou