我正在尝试开发一个代码,该代码可以帮助我创建具有自动建议和自动完成功能的下拉列表,并在列表中过滤该选项。 例如。如果键入“ a”,则下拉列表应显示所有包含“ a”的选项的结果,一旦我键入“ ab”,则下拉选项应自动过滤掉。数据是从数据库中获取的,因此范围必须是动态的,并且应该使用VBA在下拉列表中自动更新。
我尝试了几种可在网络上找到的代码,但是某些东西或其他东西丢失了,并且长期以来一直困扰于该问题。该功能适用于excel公式,但我需要通过VBA来实现。
If target.Validation.Type = xlValidateList Then
' Added this to auto select all text when activating the combox box.
xCombox.SetFocus
With xCombox
.ListFillRange = vbNullString
.LinkedCell = vbNullString
.Visible = False
End With
Dim xStr As String
Dim xArr
If target.Validation.Type = xlValidateList Then
' The target cell contains Data Validation.
target.Validation.InCellDropdown = False
' Cancel the "SelectionChange" event.
Dim Cancel As Boolean
Cancel = True
xStr = target.Validation.Formula1
xStr = Right(xStr, Len(xStr) - 1)
If xStr = vbNullString Then Exit Sub
With xCombox
.Visible = True
.Left = target.Left
.Top = target.Top
.Width = target.Width + 5
.Height = target.Height + 5
.ListFillRange = xStr
If .ListFillRange = vbNullString Then
xArr = Split(xStr, ",")
TempCombo.List = xArr
End If
.LinkedCell = target.Address
End With
xCombox.Activate
Me.TempCombo.DropDown
感谢任何建议和解决方案。
致谢。
答案 0 :(得分:0)
正如OP所提到的,尝试使用ComboBox来显示过滤后的数据...:
在我的项目中,我同时拥有textbox
和listbox
(后者也可以是combobox
。该文本框已打开,供用户在其中键入过滤器,而列表框显示已过滤的项目,这些项目是从数据库中导入的。
文本框(在本例中为machbox
)具有一个KeyUp event,它依次更新了列表框:
Private Sub machbox_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
'If what has been typed is a number / Delete / Backspace
If KeyCode = vbKeyBack Or KeyCode = vbKeyDelete Or (47 < KeyCode And KeyCode < 58) Or KeyCode Like vbKeyNumpad & "*" Then
If Len(Me.machbox.Value) > 3 Then nlist 'prevents the query from firing when the filter is too broad
End If
End Sub
然后填充列表框的子项:
Sub nlist
'Set F as the filter, which is the value of the listbox
F = machbox.Value
'I have ommited the code that connects to the DB
'Clear the listbox so it won't keep the records from the previous filter
Me.ListBox1.Clear
'Execute the query and parse the records to the listbox
Set rs = cnn.Execute("Select * From Table Where Code = '" & F & "'") 'example query
If (rs.RecordCount <> 0) Then
Do While Not rs.EOF
Me.ListBox1.AddItem (rs.Fields(0).Value)
rs.MoveNext
Loop
End If
End Sub