繁体   English   中英

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

[英]How to filter listbox values based on a Textbox value

我在用户表单上有一个文本框和一个列表框。 我想根据我在文本框中输入的值过滤列表框中的值。 名为 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

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

最后的行If Me.ListBox1.ListCount = 1 Then Me.ListBox1.Selected(0) = True并不是真正必要的,而是为了您的方便。 如果ListBox中只有 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

来源,示例文件链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM