| How to quickly search ListBox and ComboBox controls |
Applies To |
|
| OS: VB: |
NT, 9x, 2000 5, 6 |
|
| Add the following to a .BAS, .FRM or .CLS |
|---|
Private Declare Function SendMessage Lib "USER32" Alias "SendMessageA" _
(ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As _
Integer, ByVal lParam As Any) As Long
'constants for searching the ComboBox
Private Const CB_FINDSTRINGEXACT = &H158
Private Const CB_FINDSTRING = &H14C
'constants for searching the ListBox
Private Const LB_FINDSTRINGEXACT = &H1A2
Private Const LB_FINDSTRING = &H18F
'function to get find an item in the ComboBox
Public Function GetComboBoxIndex(hWnd As Long, SearchKey As String, Optional FindExactMatch As Boolean = True) As Long
'Parameters:
' hWnd - the handle to the ComboBox control. Usage: Combo1.hWnd
' SearchKey - item that you would like to search for. Can be any string - case doesn't matter when searching
' Optional FindExactMatch - Default is True. Pass False to find a partial match
'Return:
' Returns the index of the found match. If the match is not found, -1 is returned
'Usage:
' Combo1.ListIndex = GetComboBoxIndex(Combo1.hWnd, "Test Item")
' Combo1.ListIndex = GetComboBoxIndex(Combo1.hWnd, "Test Item", False)
If FindExactMatch Then
GetComboBoxIndex = SendMessage(hWnd, CB_FINDSTRINGEXACT, -1, ByVal SearchKey)
Else
GetComboBoxIndex = SendMessage(hWnd, CB_FINDSTRING, -1, ByVal SearchKey)
End If
End Function
'function to get find an item in the Listbox
Public Function GetListBoxIndex(hWnd As Long, SearchKey As String, Optional FindExactMatch As Boolean = True) As Long
'Parameters:
' hWnd - the handle to the ListBox control. Usage: List1.hWnd
' SearchKey - item that you would like to search for. Can be any string - case doesn't matter when searching
' Optional FindExactMatch - Default is True. Pass False to find a partial match
'Return:
' Returns the index of the found match. If the match is not found, -1 is returned
'Usage:
' Combo1.ListIndex = GetComboBoxIndex(List1.hWnd, "Test Item")
' Combo1.ListIndex = GetComboBoxIndex(List1.hWnd, "Test Item", False)
If FindExactMatch Then
GetListBoxIndex = SendMessage(hWnd, LB_FINDSTRINGEXACT, -1, ByVal SearchKey)
Else
GetListBoxIndex = SendMessage(hWnd, LB_FINDSTRING, -1, ByVal SearchKey)
End If
End Function