I wanted to use ListBox so that I can select the entry rather than TextBox

假如想象 提交于 2019-12-02 14:49:34

问题


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.

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:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!