使用VBA填充下拉列表后,在Excel中输入时自动完成

3

我正在使用以下代码从另一个工作表中插入数据到下拉列表中。当用户从另一个下拉列表中选择某个选项时,就会实现这一点。

lstRow = Sheets("Data Sheet").Range("D" & Rows.Count).End(xlUp).Row
Sheets("Data Insert").Range("C3").Select
With Selection.Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="='Associated British Ports'!$G$7:$G" & lstRow
    .IgnoreBlank = False
    .InCellDropdown = True
    .InputTitle = ""
    .ErrorTitle = "Invalid Selection"
    .InputMessage = ""
    .ErrorMessage = _
    "Please select a user from the list or select New User as the configuration type."
    .ShowInput = True
    .ShowError = True
End With

我想添加一个功能,当用户输入几个字母时,它会搜索列表并消除不包含该字母的任何内容。 例如,如果下拉菜单中有以下内容: A Thomas c Smith f Graham t Evans s davids B matthews
当用户输入"th"时,剩余的值应为:
A Thomas c Smith B matthews
即使用户必须以A Th...的形式输入名称才能返回A Thomas的简化版本也可以接受,如果上述操作不可行。
我看到了这个http://www.ozgrid.com/Excel/autocomplete-validation.htm和这个Excel data validation with suggestions/autocomplete 但我不确定如何将其与上述代码集成,或者是否可能!
请问有人可以帮我吗?
谢谢!

你想要什么?你似乎遗失了问题的那一部分 - “我想要我已经看到…” - Doug Glancy
抱歉,我已经添加了它!不确定发生了什么事! - TechyChick94
1个回答

2
这是我的SAYT(即时搜索)功能。我的表单有一个列表框控件,其中包含用户列表,还有一个文本框控件,您可以使用它来搜索列表。请保留HTML标签。
Private Sub txtSearch_Change()
    Dim x As Integer

    lstUsers.ListIndex = -1
    For x = 0 To lstUsers.ListCount - 1
        lstUsers.ListIndex = x
        If InStr(1, LCase(lstUsers.Text), LCase(txtSearch.Text), vbTextCompare) > 0 _
        Or InStr(1, LCase(lstUsers.List(x, 1)), LCase(txtSearch.Text), vbTextCompare) > 0 _
        Then
            Exit Sub
        End If
    Next x
End Sub

Private Sub txtSearch_KeyPress(ByVal KeyAscii As msforms.ReturnInteger)
    If KeyAscii = 13 Then
        txtSearch.Text = lstUsers.Text
    End If
End Sub

当您输入时,每次按键都会触发txtSearch_Change事件,并循环遍历列表框的值,直到找到第一个匹配项并将其选择。我们还检查KeyPress事件,以查看用户是否按下Enter(ASCII 13)自动完成搜索。我的大小写不敏感(我将所有内容转换为小写),但您可以轻松修改它以使其区分大小写(甚至添加复选框,以便用户可以选择大小写敏感性!)


谢谢,我明天会尝试并告诉你 :) - TechyChick94
搜索即时响应的好方法。 - Adarsh Madrecha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接