Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

vba - How to filter listbox values based on a Textbox value

I have a textbox and a listbox on userform. I want to filter the values in listbox based on the value I enter in Textbox. Sheet named TMP has the values and I filter it based on textbox change event but it quits automatically when adding that values to listbox.

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I sure hope the following piece of code is what you are looking for.

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

Note that this sub does not make use of the AutoFilter on the sheet TMP. Therefore, the sub is a bit faster. Also, if you wish to filter your data on the sheet, this sub won't delete / change your current filter settings.

The line at the end If Me.ListBox1.ListCount = 1 Then Me.ListBox1.Selected(0) = True is not really necessary but rather for your convenience. It ensures that the item is automatically selected in the ListBox if there is only 1 item in the list.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...