Ank
Ank

Reputation: 6270

Auto complete text box in excel VBA

I am creating a excel sheet that would autocomplete a text based on the text present in a particular column. After trying to make one myself unsuccessfully, I was looking online for sample codes that I could modify and incorporate in my program. (and not plagiarize)

I downloaded Workbook1.xls from http://www.ozgrid.com/forum/showthread.php?t=144438

The code is

Option Explicit

Dim ufEventsDisabled As Boolean
Dim autoCompleteEnabled As Boolean
Dim oRange As Range

Private Sub TextBox1_Change()
    If ufEventsDisabled Then Exit Sub
    If autoCompleteEnabled Then Call myAutoComplete(TextBox1)
End Sub

Sub myAutoComplete(aTextBox As MSForms.TextBox)
    Dim RestOfCompletion As String
    On Error GoTo Halt
    With aTextBox
        If .SelStart + .SelLength = Len(.Text) Then
            RestOfCompletion = Mid(oRange.Cells(1, 1).AutoComplete(.Text), Len(.Text) + 1)
            ufEventsDisabled = True
            .Text = .Text & RestOfCompletion
            .SelStart = Len(.Text) - Len(RestOfCompletion)
            .SelLength = Len(RestOfCompletion)
        End If
    End With
Halt:
ufEventsDisabled = False
On Error GoTo 0
End Sub

Private Sub TextBox1_AfterUpdate()
    Dim strCompleted As String
    With TextBox1
        strCompleted = oRange.AutoComplete(.Text)
        If LCase(strCompleted) = LCase(.Text) Then
            ufEventsDisabled = True
            .Text = strCompleted
            ufEventsDisabled = False
        End If
    End With
End Sub

Private Sub TextBox1_Enter()
    Set oRange = ThisWorkbook.Sheets("Sheet1").Range("f4")
End Sub

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    autoCompleteEnabled = KeyCode <> vbKeyBack
    autoCompleteEnabled = ((vbKey0 <= KeyCode) And (KeyCode <= vbKeyZ))
End Sub

Private Sub CommandButton1_Click()
    Unload Me
End Sub

Private Sub UserForm_Click()

End Sub

If you'd notice the line RestOfCompletion = Mid(oRange.Cells(1, 1).AutoComplete(.Text), Len(.Text) + 1), I was wondering what AutoComplete is doing here. Its not a in built function and is not defined anywhere. Still the code runs fine. I am very curious.

Thanks

Upvotes: 0

Views: 14029

Answers (1)

Daniel Tallentire
Daniel Tallentire

Reputation: 304

The .AutoComplete is a function of the Range object - it is based on passing the text to a range that exists elsewhere on the sheet.

You can see the documentation on this function here: http://msdn.microsoft.com/en-us/library/bb209667(v=office.12).aspx

The myAutoComplete function handles the finding of the autocomplete data against the range if it exists, and the other pieces in the code are for highlighting the correct piece of text.

Upvotes: 2

Related Questions