How to auto complete text box in VB6


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 Boolean

Private Function AutoCompletar_TextBox( _
textBox As Variant, pArrValues() As String)

Dim i As Integer
Dim posSelect As Integer

Select 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 i

End 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 Sub

Private 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 Sub

Public Sub SaveValueToFile(Text1 As Variant)
If Text1 <> “” Then
Call saveValues(arrValues, Text1.Text)
Text1.Text = “”
End If
End Sub

Public 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)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.