过滤仅从TextBox文本中匹配ListBox Excel中的结果

时间:2017-09-15 01:49:23

标签: excel vba excel-vba

我有一个带有文本框和列表框的用户表单。我希望用户能够在文本框中输入文本,并根据他们的输入过滤列表框过滤结果。

到目前为止,我已设法让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

1 个答案:

答案 0 :(得分:1)

尝试使用退出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

Found a better code to filter a listbox.

相关问题