VB Notebook Main Page VB Notebook Files VB Notebook Function Library VB Notebook Articles VB Notebook Links VB Notebook

VBNotebook Home | Functions | List Box Search

This function searches for the specified string in the list box. The routine can do a Find Exact search where the contents must exactly match those in the search string, a Find Partial where the routine searches for the first match on the starting characters of the string, and a Wild Card search that uses the VB Like function to search the box. The routine returns the position index of the item if it is found, -1 if it is not found.

First, in General|Declarations...
__________________________________________________________________________________________

'
' List Search Enum Constants
'

Public Enum ListSearchTypes
    lstFindExact
    lstFindPartial
    lstWildCard

End Enum
'
' Windows Message Constants
'

Private Const
LB_FINDSTRINGEXACT = &H1A2
Private Const
LB_FINDSTRING = &H18F
'
' API Calls
'

Private 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

__________________________________________________________________________________________

And now the routine. Note that the list box is passed "As Object". This is done when the routine has been placed in a Global Multiuse function library in a DLL. If you place this routine in a standard module in your project, you can change the "As Object" to "As ListBox" and remove the "If TypeOf" check in the code.
__________________________________________________________________________________________

Public Function SearchListBox(lstSearch As Object, ByVal sSearch As String, _
                              Optional ByVal nSearchtype As ListSearchTypes = lstFindExact) _                               As Integer

    Dim nLoop As Long
    Dim nEnd As Long

    If TypeOf lstSearch Is ListBox Then
        Select Case nSearchtype
            Case lstFindPartial
                SearchListBox = SendMessageByString(lstSearch.hwnd, LB_FINDSTRING, _
                                -1, sSearch)
            Case lstFindExact
                SearchListBox = SendMessageByString(lstSearch.hwnd, LB_FINDSTRINGEXACT, _
                                -1, sSearch)
            Case lstWildCard
                nEnd = lstSearch.ListCount - 1
                SearchListBox = -1
                For nLoop = 0 To nEnd
                    If lstSearch.List(nLoop) Like sSearch Then
                        SearchListBox = nLoop
                        Exit For
                    End If
                Next
            Case Else
                SearchListBox = -1
        End Select
    Else
        SearchListBox = -1
    End If
End Function

__________________________________________________________________________________________

Copyright 2000-2005, J. Frank Carr