| '(c) Richard C. Yarnell 1998 ' ryarnell@andrew.cmu.edu Option Explicit Dim bOKToComplete As Boolean Dim bSelecting As Boolean Private Sub cmbData_Change() Dim i As Integer Dim iCurLen As Integer 'only proceed if it is ok to run the auto-complete If bOKToComplete Then 'set this flag to False so the procedure will not run recursively 'when the text is changed below, this event will be trigged again, ' but this will prevent this code from running multiple times bOKToComplete = False 'get the length of the text currently entered iCurLen = Len(cmbData.Text) 'cycle through all items in the combo box For i = 0 To cmbData.ListCount - 1 'if the first iCurLen letters of the item in the 'combo ' box are the same as the text entered then proceed If Mid(cmbData.List(i), 1, iCurLen) = cmbData.Text Then 'set the text to that item cmbData.Text = cmbData.List(i) 'put the cursor back where it was before the auto-complete began cmbData.SelStart = iCurLen 'and then select the rest of the text '(this is the text that was added by auto-complete 'your typing will automatically overwrite this new text ' if you type anything else cmbData.SelLength = Len(cmbData.Text) - iCurLen 'exit the for loop because we already found a matching item Exit For End If Next i End If 'set this flag back to True so this event will run the next time bOKToComplete = True End Sub Private Sub cmbData_Click() ItemSelected (cmbData.Text) End Sub Private Sub cmbData_KeyDown(KeyCode As Integer, Shift As Integer) 'this event fires before the cmbData_Change event so we can "trap" certain keys here If KeyCode = vbKeyBack Or KeyCode = vbKeyDelete Then 'if BackSpace or Delete are pressed set this flag to 'False so auto-complete will not run bOKToComplete = False ElseIf KeyCode = vbKeyReturn Then 'if enter is pressed then call the procedure 'to select that item ItemSelected (cmbData.Text) Else 'allow all other keys to go through and 'set this flag to True bOKToComplete = True End If End Sub Private Sub Form_Load() bOKToComplete = True cmbData.AddItem "Smith" cmbData.AddItem "Jones" cmbData.AddItem "Williams" End Sub Public Sub ItemSelected(sText As String) Dim i As Integer 'only proceed if the code is not already running If bSelecting = False Then 'set this flag to True to prevent recursive 'calls to this procedure bSelecting = True 'cycle through all items in the combo box For i = 0 To cmbData.ListCount - 1 'proceed only if that item matches the one selected If cmbData.List(i) = sText Then 'remove that item cmbData.RemoveItem i 'put it back in the combo box, but at the top cmbData.AddItem sText, 0 'the item we want selected is now at the top, 'so specify that item to be the selected item cmbData.ListIndex = 0 'we found a match, so we can quit now Exit For End If Next i End If 'this procedure is done, so set this 'flag to False so we can call it again bSelecting = False End Sub |