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

VBNotebook Home | Functions | Combo Box Search

This function searches for the specified string in the combo 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
CB_FINDSTRING = &H14C
Private Const
CB_FINDSTRINGEXACT = &H158
'
' 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 combo 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 ComboBox" and remove the "If TypeOf" check in the code. __________________________________________________________________________________________

Public Function SearchCombo(cboSearch As Object, ByVal sSearch As String, _
                            Optional ByVal nSearchtype As ListSearchTypes = lstFindExact) _
                            As Integer
    Dim nLoop As Long
    Dim nEnd As Long

    If TypeOf cboSearch Is ComboBox Then
        Select Case nSearchtype
            Case lstFindPartial
                SearchCombo = SendMessageByString(cboSearch.hwnd, CB_FINDSTRING, -1, sSearch)
            Case lstFindExact
                SearchCombo = SendMessageByString(cboSearch.hwnd, _
                                                  CB_FINDSTRINGEXACT
, -1, sSearch)
            Case lstWildCard
                nEnd = cboSearch.ListCount - 1
                SearchCombo = -1
                For nLoop = 0 To nEnd
                    If cboSearch.List(nLoop) Like sSearch Then
                        SearchCombo = nLoop
                        Exit For
                    End If
                Next
            Case Else
                SearchCombo = -1
        End Select
    Else
        SearchCombo = -1
    End If
End Function

__________________________________________________________________________________________

Copyright 2000-2005, J. Frank Carr