如何根据文本框值过滤列表框值

How to filter listbox values based on a Textbox value

我在用户窗体上有一个文本框和一个列表框。我想根据我在文本框中输入的值过滤列表框中的值。 Sheet 命名的 TMP 具有值,我根据文本框更改事件对其进行过滤,但在将这些值添加到列表框时它会自动退出。

Private Sub Textbox1_Change()
'On Error Resume Next
Dim fCell As Range, MyArr As Variant, i As Long

With TMP
    .AutoFilterMode = False
    .Range("A1").AutoFilter
    .Range("A1").AutoFilter Field:=1, Criteria1:=Me.TextBox1.Value
End With

ListBox1.RowSource = ""
i = 0

For Each fCell In TMP.Range("A1:A" & TMP.Range("A" & TMP.Rows.Count).End(xlUp).Row).SpecialCells(xlCellTypeVisible)
    Me.ListBox1.AddItem fCell.Value, i
     i = i + 1
Next fCell


End Sub

我当然希望下面这段代码是您要找的。

Private Sub Textbox1_Change()

Dim i As Long
Dim arrList As Variant

Me.ListBox1.Clear
If TMP.Range("A" & TMP.Rows.Count).End(xlUp).Row > 1 And Trim(Me.TextBox1.Value) <> vbNullString Then
    arrList = TMP.Range("A1:A" & TMP.Range("A" & TMP.Rows.Count).End(xlUp).Row).Value2
    For i = LBound(arrList) To UBound(arrList)
        If InStr(1, arrList(i, 1), Trim(Me.TextBox1.Value), vbTextCompare) Then
            Me.ListBox1.AddItem arrList(i, 1)
        End If
    Next i
End If
If Me.ListBox1.ListCount = 1 Then Me.ListBox1.Selected(0) = True

End Sub

请注意,此子未使用 sheet TMP 上的 AutoFilter。因此,潜艇要快一点。此外,如果您希望在 sheet 上过滤您的数据,此子不会删除/更改您当前的过滤器设置。

末尾的行 If Me.ListBox1.ListCount = 1 Then Me.ListBox1.Selected(0) = True 并不是必需的,而是为了您的方便。如果列表中只有 1 个项目,它确保在 ListBox 中自动选择该项目。

根据文本框中的值,可以在多列列表框中过滤数据。 此外,可以从组合框中选择要过滤的列表框列。

例如,VBA 通过单击“搜索”按钮在列表框的第一列(带有名称的列)中搜索而触发的代码:

deg2 = TextBox13.Value
Select Case ComboBox1.Value
Case "Name"
For sat = 2 To Cells(Rows.Count, 1).End(xlUp).Row
Set deg1 = Cells(sat, "A")
If UCase(deg1) Like UCase(deg2) & "*" Then
ListBox1.AddItem
ListBox1.List(s, 0) = Cells(sat, "A")
ListBox1.List(s, 1) = Cells(sat, "B")
ListBox1.List(s, 2) = Cells(sat, "C")
ListBox1.List(s, 3) = Cells(sat, "D")
ListBox1.List(s, 4) = Cells(sat, "E")
ListBox1.List(s, 5) = Cells(sat, "F")
ListBox1.List(s, 6) = Cells(sat, "G")
ListBox1.List(s, 7) = Cells(sat, "H")
ListBox1.List(s, 8) = Cells(sat, "I")
ListBox1.List(s, 9) = Cells(sat, "J")
ListBox1.List(s, 10) = Cells(sat, "K")
ListBox1.List(s, 11) = Cells(sat, "L")
s = s + 1
End If: Next

Source,sample file link