Ok, we know. Every website and their mother has
this code, but the site wouldn't be complete without it. As everyone knows when the number of items in the Listbox or ComboBox gets
pretty high, say more than 500, it takes a long time to
iterate through the list and items and find what you want. Here is a quicker (much,
much quicker) way to search. Just pop the code below into your code and
then call it from wherever you want to search lists.
| 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