Excel 2013 with vba:
I have 2 columns in Sheet1 Column A has NBA Players while Column B shows their Jersey Numbers. If I type 2 in txtNumber it will display Players with number 2 on their Jerseys. It works on that way, However I can't click or select the entry or data. I'm thinking that Listbox would be a better replacement for TextBox, however I just don't know how to use the listbox. Please help.
code:
Private Sub txtNumber_Change()
Dim mySheet As Worksheet 'declaring mySheet as the Worksheet...
Dim x
Dim i As Long
Dim str As String
Set mySheet = Sheets("Sheet1")
x = mySheet.Range("A1").CurrentRegion.Value
For i = 2 To UBound(x, 1)
If x(i, 2) = Val(txtNumber.Value) Then
If str = "" Then
str = x(i, 1)
Else
str = str & vbNewLine & x(i, 1)
End If
End If
Next i
If str <> "" Then
txtName.Value = str
Else
txtName.Value = "Match not found"
End If
End Sub
Assuming the name of the listbox is ListBox1 then you may try something like this...
Private Sub txtNumber_Change()
Dim mySheet As Worksheet 'declaring mySheet as the Worksheet...
Dim x, dict
Dim i As Long
Dim cnt As Long
Set mySheet = Sheets("Sheet1")
ListBox1.Clear
x = mySheet.Range("A1").CurrentRegion.Value
Set dict = CreateObject("Scripting.Dictionary")
If Application.CountIf(mySheet.Columns(2), txtNumber.Value) > 0 Then
For i = 2 To UBound(x, 1)
If x(i, 2) = Val(txtNumber.Value) Then
dict.Item(x(i, 1)) = ""
End If
Next i
ListBox1.List = dict.keys
Else
ListBox1.AddItem "Match not found"
End If
End Sub
来源:https://stackoverflow.com/questions/43792983/i-wanted-to-use-listbox-so-that-i-can-select-the-entry-rather-than-textbox