I would like to implement a search function in a listbox in a userform getting a better view of the many columns and unfortunately I can't find a solution.
The optimal solution would be, if I could search in a textbox for any row content (up to 12 columns containing data like e.g. name, ID, position, organization, ...) and the listbox would automatically update itself showing all matching entries.
In UserForm_Initialize
I filled the listbox as follows:
Private Sub UserForm_Initialize()
With UserForm1
.StartUpPosition = 1
.Top = 1
.Left = 1
End With
Dim last As Integer
last = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).row + 1
ListBox1.ColumnCount = 12
ListBox1.ColumnHeads = True
ListBox1.ColumnWidths = "30;50;200;60;30;110;110;90;50;40;50;80;60"
ListBox1.RowSource = "A2:M" & last
End Sub
I imagined the search function to filter the listbox depending on the input in Textbox1
.
After long research and consideration (unfortunately I am an absolute vba amateur) the following code was created:
Private Sub TextBox1_Change()
Dim i As Long
On Error Resume Next
Me.TextBox1.Text = StrConv(Me.TextBox1.Text, vbProperCase)
Me.ListBox1.Clear
For i = 2 To Application.WorksheetFunction.CountA(ActiveSheet.Range("A:A"))
For x = 1 To 12
a = Len(Me.TextBox1.Text)
If Left(ActiveSheet.Cells(i, x).Value, a) = Me.TextBox1.Text And Me.TextBox1.Text <> "" Then
Me.ListBox1.AddItem ActiveSheet.Cells(i, x).Value
For c = 1 To 12
Me.ListBox1.List(ListBox1.ListCount - 1, c) = ActiveSheet.Cells(i, c + 1).Value
Next c
End If
Next x
Next i
End Sub
My question: Does anyone have a smarter / leaner solution or could maybe help to get my code working as currently I get the runtime error '9'
on execution.