Private Declare Function SendMessage Lib "User32" Alias "SendMessageA" (ByVal _
HWnd As Long, ByVal msg As Long, ByVal wParam As Long, _
lParam As Any) As Long
Const LB_FINDSTRING = &H18F
Private Declare Function GetFocus Lib "user32.dll" () As Long
Private Declare Function IsWindow Lib "user32.dll" (ByVal HWnd As Long) As Long
' this is a form-level variable
Dim DoSearch As Integer
Dim HWnd As Long
Sub List1_Click()
' user selected a new item
' (also activated by Text1_KeyDown)
Text1.Text = List1.Text
End Sub
Private Sub List1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
' keep the two controls synchronized
Text1.Text = List1.Text
End Sub
Private Sub List1_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
' keep the two controls synchronized
Text1.Text = List1.Text
End Sub
Sub Text1_Change()
Static active As Boolean
Dim index As Integer
Dim search As String
Dim found As Integer
' avoid recursive calls
If active Or DoSearch = False Then Exit Sub
active = True
' search is not case sensitive
search = UCase$(Text1.Text)
found = -1
' search the first item in the listbox
' that matches the search string in the textbox
found = SendMessage(HWnd, LB_FINDSTRING, -1, ByVal search)
If found >= 0 Then
' make the found value the current item
List1.ListIndex = found
Text1.Text = List1
' select the remaining characters
Text1.SelStart = Len(search)
Text1.SelLength = 999
End If
active = False
End Sub
Private Sub Text1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If Shift Then
' do nothing if a shift key is pressed
ElseIf KeyCode = vbKeyUp Then
' move on previous item
If List1.ListIndex > 0 Then
List1.ListIndex = List1.ListIndex - 1
End If
KeyCode = 0
ElseIf KeyCode = vbKeyDown Then
' move on next item
If List1.ListIndex < List1.ListCount - 1 Then
List1.ListIndex = List1.ListIndex + 1
End If
KeyCode = 0
End If
End Sub
Private Sub Text1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii = 8 And Text1.SelStart > 0 Then
' if BackSpace has be pressed, trim one
' character off the search string
DoSearch = False
Text1.Text = Left$(Text1.Text, Text1.SelStart)
Text1.SelStart = Len(Text1.Text)
Else
DoSearch = True
End If
End Sub
Private Sub UserForm_Initialize()
Me.List1.SetFocus
HWnd = GetFocus
End Sub