How to add a auto complete feature in Microsoft Visual Basic 6 ?
With the help of some creepy code, we can save the entry into a data file temporarily and later we can use them as input for auto complete the name/place/text.
The code is work with Text box as well as Combo box. Drop the following code to a module call the methods defined.
Private arrValues() As String
Private bKeyBack As BooleanPrivate Function AutoCompletar_TextBox( _
textBox As Variant, pArrValues() As String)Dim i As Integer
Dim posSelect As IntegerSelect Case (bKeyBack Or Len(textBox.Text) = 0)
Case True
bKeyBack = False
Exit Function
End Select
With textBox
For i = 0 To UBound(pArrValues)
If InStr(1, pArrValues(i), .Text, vbTextCompare) = 1 Then
posSelect = .SelStart
.Text = pArrValues(i)
.SelStart = posSelect
.SelLength = Len(.Text) – posSelect
Exit For
End If
Next iEnd With
End Function
Private Sub saveValues(pArrValues() As String, NewValue As String)
Dim lIndex As Long
lIndex = UBound(pArrValues) + 1
ReDim Preserve pArrValues(lIndex)
pArrValues(lIndex) = NewValue
Open App.Path & “\history.dat” For Output As #1
Dim i As Integer
For i = 0 To UBound(pArrValues)
If pArrValues(i) <> “” Then
Print #1, pArrValues(i)
End If
Next
Close
End SubPrivate Sub LoadValues(pArrValues() As String)
Dim lIndex As Long
Dim sValue As String
Dim sPath As String
sPath = App.Path & “\history.dat”
If Len(Dir(sPath)) = 0 Then
Exit Sub
End If
Open App.Path & “\history.dat” For Input As #1
While Not EOF(1)
Line Input #1, sValue
ReDim Preserve pArrValues(lIndex)
If sValue <> “” Then
pArrValues(lIndex) = sValue
End If
lIndex = lIndex + 1
Wend
Close
End Sub
Public Sub LoadValuesToMem()
ReDim arrValues(0)
Call LoadValues(arrValues)End Sub
Public Sub KeyDown(ky As Integer, Optional Text1 As Variant)
Select Case ky
Case vbKeyBack, vbKeyDelete
Select Case Len(Text1.Text)
Case Is <> 0
bKeyBack = True
End Select
End Select
End SubPublic Sub SaveValueToFile(Text1 As Variant)
If Text1 <> “” Then
Call saveValues(arrValues, Text1.Text)
Text1.Text = “”
End If
End SubPublic Sub Text_Change(Text1 As Variant)
Call AutoCompletar_TextBox(Text1, arrValues)End Sub
How to use
1. Click event
SaveValueToFile text1
2.Load event
Call LoadValuesToMem
3.Change event
Call Text_Change(text1)
4.Keydown
Call KeyDown(KeyCode, text1)