【问题标题】:How to filter listbox values based on a Textbox value如何根据文本框值过滤列表框值
【发布时间】:2017-08-10 07:03:59
【问题描述】:

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

【问题讨论】:

    标签: vba excel filter listbox userform


    【解决方案1】:

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

    例如,通过点击“搜索”按钮触发的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

    【讨论】:

      【解决方案2】:

      我当然希望以下代码是您正在寻找的。​​p>

      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。因此,子速度要快一些。此外,如果您希望过滤工作表上的数据,此子程序不会删除/更改您当前的过滤器设置。

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

      【讨论】:

      • 哇,你太棒了。非常感谢!
      • 多列Listbox怎么办?
      • 对于多列列表框,可以将 Me.ListBox1.AddItem arrList(i, 1) 替换为 Me.Listbox.AddItem Listbox.List(0, 0) = arrList(i, 1) Listbox.List (0, 1) = arrList(i, 2)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-08
      相关资源
      最近更新 更多