ComboBox KeyPress Event Handler limits text typed to only allow an item from the list
This combo box event handler will limit the text typed to only items available from the list. This essentially makes the control into a dropdown list but allows the items to be selected by typing as well as clicking.
Inputs
This will work on any ComboBox. It assumes the control is called Combo1 but obviously, this can be changed.
Rate ComboBox KeyPress Event Handler limits text typed to only allow an item from the list
(4(4 Vote))
' function to intercept keypresses to combo box and allow
' only valid keys (such as are in list)
'
Private Sub Combo1_KeyPress(KeyAscii As Integer)
Dim NewText As String
Dim ValidCount As Integer
Dim ValidValue As String
' do only if key pressed is printable character
If KeyAscii >= 32 And KeyAscii <> 127 Then
' predict new text after keypress
NewText = LCase(Left(Combo1.Text, Combo1.SelStart) + Chr(KeyAscii) + Mid(Combo1.Text, Combo1.SelStart + Combo1.SelLength + 1))
' find number of matches in combo list
ValidCount = 0
ValidValue = ""
For i = 0 To Combo1.ListCount - 1
If NewText = LCase(Left(Combo1.List(i), Len(NewText))) Then
ValidCount = ValidCount + 1
ValidValue = Combo1.List(i)
End If
Next
' cancel keypress if invalid
If ValidCount <= 1 Then KeyAscii = 0
' select if one match only
If ValidCount = 1 Then
Combo1.Text = ValidValue
Combo1.SelStart = 0
Combo1.SelLength = Len(ValidValue)
End If
End If
End Sub
ComboBox KeyPress Event Handler limits text typed to only allow an item from the list Comments
No comments yet — be the first to post one!
Post a Comment