我正在创建一个Excel工作表,它会根据特定列中的文本自动完成文本。在尝试使自己失败之后,我正在网上查找我可以修改并合并到我的程序中的示例代码。 (而不是抄袭)
我从http://www.ozgrid.com/forum/showthread.php?t=144438
下载了Workbook1.xls代码是
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
如果您注意到RestOfCompletion = Mid(oRange.Cells(1,1).AutoComplete(.Text),Len(.Text)+ 1),我想知道AutoComplete在这里做了什么。它不是一个内置的功能,并没有在任何地方定义。代码运行良好。我很好奇。
由于
答案 0 :(得分:2)
.AutoComplete是Range对象的一个函数 - 它基于将文本传递到工作表上其他位置的范围。
您可以在此处查看有关此功能的文档: http://msdn.microsoft.com/en-us/library/bb209667(v=office.12).aspx
myAutoComplete函数根据范围处理自动完成数据的查找(如果存在),代码中的其他部分用于突出显示正确的文本。