[RESOLVED] Combo box auto complete (and the ability to correct typos)
I am using the code by Comintern in the following link to auto complete a combo box
http://www.vbforums.com/showthread.p...ight=Combo+Box
The code works beautifully except that if I type the letter J instead of K it will not allow me to backspace. Anybody have any ideas how to fix this.
I really have not had a change to figure something out yet.
Thank You
Re: Combo box auto complete (and the ability to correct typos)
This is the code I use, see if it works for you:
Code:
Option Explicit
Private Declare Function SendMessageStr Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, _
ByVal wMsg As Long, _
ByVal wParam As Long, _
ByVal lParam As String) _
As Long
Private Const CB_FINDSTRING = &H14C
Private bBkSpOrDel As Boolean
Private Sub Form_Activate()
Dim i As Integer, j As Integer, k As Integer, l As Integer
Dim s As String, t As String
Randomize
For i = 1 To 4000
k = 1 + 10 * Rnd
s = ""
For j = 1 To k
l = 97 + 25 * Rnd
t = Chr(l)
s = s & t
Next
Combo1.AddItem s
Next
End Sub
Private Sub Combo1_Change()
Dim lRet As Long
Dim lSelStart As Long
If bBkSpOrDel Then Exit Sub
With Combo1
lRet = SendMessageStr(.hwnd, CB_FINDSTRING, 0, .Text)
lSelStart = .SelStart
If lRet >= 0 Then
.ListIndex = lRet
.SelStart = lSelStart
.SelLength = Len(.Text)
End If
End With
End Sub
Private Sub Combo1_KeyDown(KeyCode As Integer, Shift As Integer)
Select Case KeyCode
Case vbKeyDelete, vbKeyBack
bBkSpOrDel = True
Case Else
bBkSpOrDel = False
End Select
End Sub
Re: Combo box auto complete (and the ability to correct typos)
Another way
vb Code:
Option Explicit
Private blnBackSpace As Boolean
Private Sub Combo1_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyBack Or KeyCode = vbKeyDelete Then
If Combo1.Text <> vbNullString Then
'Let the Change event know that it shouldn't respond to this change.
blnBackSpace = True
End If
End If
End Sub
Private Sub Combo1_Change()
Dim i As Long
Dim lngText As Long
'If firing in response to a backspace or delete, don't run the auto-complete
'complete code. (Otherwise you wouldn't be able to back up.)
If blnBackSpace = True Or Combo1.Text = vbNullString Then
blnBackSpace = False
Exit Sub
End If
'Run through the available items and grab the first matching one.
For i = 0 To Combo1.ListCount - 1
If InStr(1, Combo1.List(i), Combo1.Text, vbTextCompare) = 1 Then
'Save the SelStart property.
lngText = Combo1.SelStart
Combo1.Text = Combo1.List(i)
'Set the selection in the combo.
Combo1.SelStart = lngText
Combo1.SelLength = Len(Combo1.Text) - lngText
Exit For
End If
Next
End Sub
Re: Combo box auto complete (and the ability to correct typos)
Thank you Hack.
That is fairly close to what I want. That will do for now