我想使用ListBox,以便我可以选择条目而不是TextBox

时间:2017-05-04 21:23:26

标签: combobox listbox

Excel 2013 with vba:

我在Sheet1中有2列A列有NBA球员,B栏有球衣号码。如果我在txtNumber中键入2,它将在其球衣上显示数字为2的球员。它以这种方式工作,但我无法点击或选择条目或数据。我认为Listbox会更好地替代TextBox,但我不知道如何使用列表框。请帮忙。

Screenshot

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

1 个答案:

答案 0 :(得分:0)

假设列表框的名称是ListBox1,那么您可以尝试这样的事情......

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