[英]Filter Only matching results in ListBox Excel from TextBox text
我有一个带有文本框和列表框的用户表单。 我希望用户能够在文本框中输入文本,并让列表框根据输入的内容过滤结果。
到目前为止,我设法使ListBox突出显示列表中的匹配结果,但没有过滤掉不匹配的结果。 我还遇到了代码无法识别多个匹配记录的问题,不确定是否需要添加什么才能使此事情发生。
Private Sub TextBox3_Change()
'searches ListBox3 for match and hightlights result. Need to filter results.
Dim i As Long
Dim sFind As String
sFind = Me.TextBox3.Text
If Len(sFind) = 0 Then
Me.ListBox3.ListIndex = -1
Me.ListBox3.TopIndex = 0
Else
For i = 0 To Me.ListBox3.ListCount - 1
If UCase(Left(Me.ListBox3.List(i), Len(sFind))) = UCase(sFind) Then
Me.ListBox3.TopIndex = i
Me.ListBox3.ListIndex = i
Exit For
End If
Next i
End If
End Sub
尝试使用此代码,该代码在退出textbox3时有效,否则将在键入时进行一些过滤,并可能导致错误。
Private Sub TextBox3_Exit(ByVal Cancel As MSForms.ReturnBoolean)
For i = ListBox1.ListCount - 1 To 0 Step -1
If Not ListBox1.List(i) = TextBox3 Then ListBox1.RemoveItem (i)
Next i
End Sub
并且该循环是使用递归循环进行的,否则会出现错误。
Private Sub TextBox3_Exit(ByVal Cancel As MSForms.ReturnBoolean)
For i = ListBox1.ListCount - 1 To 0 Step -1
If InStr(1, ListBox1.List(i), TextBox3) = 0 Then ListBox1.RemoveItem (i)
Next i
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.