Well, after my initial response in this thread, I became curious as to how
to accomplish this task. I came up with a workable solution. The following
code assumes that the values you wish to present to the user are present in
a table or query (or link to table or query).
Note that in the form, a global boolean variable is dimensioned to be used
for validation between the two events from the text box. In the KeyPress
event, it's set to true if character is pressed and ignored otherwise. In
the Change event, the flag is used to determine if either the keycode is
valid or if the text is being changed programmatically from the IntelliSense
procedure. Both events must be used in conjunction with the global boolean
to ensure proper processing.
Here's the code:
In the form:
----------
Option Compare Database
Option Explicit
Dim blnLookup As Boolean ' Global lookup flag
Private Sub txtMyText_Change()
If blnLookup Then
' Turn off lookup flag to keep from looping back
' when programmatically changing textbox contents
blnLookup = False
Call IntelliSense(txtMyText, "qryTest", "First")
End If
End Sub
Private Sub txtMyText_KeyPress(KeyAscii As Integer)
' If the keycode < 33, ignore it
blnLookup = Not Eval(KeyAscii < 33)
End Sub
----------
In a separate module:
----------
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~
' Procedure : IntelliSense
' Date : 7/21/2003
' Author : Glen Appleton
' Purpose : Present user with "first match" lookup value in a textbox
' Returns :
' Usage : Call IntelliSense(MyTextBox, MyTableOrQuery, MyFieldName)
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~
Sub IntelliSense(MyTextBox As TextBox, TableName As String, FieldName As
String)
Dim intUserChars As Integer ' Count of characters typed
Dim intLength As Integer ' Count of result characters
Dim strSQL As String ' SQL string for recordset
Dim rsTest As DAO.Recordset ' Recordset (Data Access Object)
Dim strResult As String ' Result of lookup
' Get the first match (if any)
strSQL = "SELECT [" & FieldName & "] from " & TableName & " " & _
"WHERE ([" & FieldName & "] Like '" & MyTextBox.Text & "*') " &
_
"Order By " & FieldName & ";"
Set rsTest = CurrentDb.OpenRecordset(strSQL)
With rsTest
If Not .RecordCount = 0 Then strResult = .Fields(FieldName).Value
End With
Set rsTest = Nothing
' If a matching value was found, present it to the user
If Not strResult = "" Then
With MyTextBox
' Get the number of characters the user actually typed
intUserChars = Len(.Text)
' Get the size of the result
intLength = Len(strResult)
' Assign the result to the textbox
.Text = strResult
' Select the portion of the text the user didn't enter
.SelStart = intUserChars
.SelLength = intLength - intUserChars
End With
End If
End Sub
----------
If you have any comments or questions about the procedures above, please let
me know and I'll try to explain my logic. :~)-
Hope this helps,
- Glen