Search code examples
excelvbauserform

Autofill listbox from textbox text VBA


I want a userform where as text is being typed into textbox1, possible values that match the text from the sheet "Data" populate listbox1 and similarly for textbox2 and listbox2. Currently when I type in textbox1, it's filling listbox2 with values from column A in the sheet that is open, instead of the sheet "Data".

Private Sub TextBox1_Change()
Dim i As Integer, ws As Worksheet
ListBox1.Visible = True

Set ws = Sheets("Data")
    For i = 2 To Sheets("Data").Range("D6000").End(xlUp).Row
        If UCase(Left(ws.Cells(i, 1), Len(TextBox1.Text))) = UCase(TextBox1.Text) Then
            ListBox1.AddItem Cells(i, 1)
            End If
            Next i
End Sub

Private Sub TextBox2_Change()
Dim i As Integer, ws As Worksheet
ListBox2.Visible = True
Set ws = Sheets("Data")
    For i = 2 To Sheets("Data").Range("B6000").End(xlUp).Row
        If UCase(Left(ws.Cells(i, 1), Len(TextBox2.Text))) = UCase(TextBox2.Text) Then
            ListBox2.AddItem Cells(i, 1)
            End If
            Next i
End Sub

Edit: What I ended up using:

Private Sub TextBox1_Change()
Dim i As Long
Dim arrList As Variant

Me.ListBox1.Clear
If Sheet7.Range("D" & Sheet7.Rows.Count).End(xlUp).Row > 1 And Trim(Me.TextBox1.Value) <> vbNullString Then
    arrList = Sheet7.Range("D1:D" & Sheet7.Range("D" & Sheet7.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
Private Sub TextBox2_Change()

Dim i As Long
Dim arrLists As Variant

Me.ListBox2.Clear
If Sheet7.Range("B" & Sheet7.Rows.Count).End(xlUp).Row > 1 And Trim(Me.TextBox2.Value) <> vbNullString Then
    arrLists = Sheet7.Range("B1:B" & Sheet7.Range("B" & Sheet7.Rows.Count).End(xlUp).Row).Value2
    For i = LBound(arrLists) To UBound(arrLists)
        If InStr(1, arrLists(i, 1), Trim(Me.TextBox2.Value), vbTextCompare) Then
            Me.ListBox2.AddItem arrLists(i, 1)
        End If
    Next i
End If
If Me.ListBox2.ListCount = 1 Then Me.ListBox2.Selected(0) = True

End Sub

Solution

  • Use ws.Cells(i, 1) instead of Cells(i, 1).
    Also, should the part concerning ListBox2 be moved to TextBox2_Change() ?