从在Excel VBA中输入到TextBox的搜索条件填充ListBox

时间:2015-05-18 10:37:01

标签: excel vba excel-vba listbox userform

之前我已经发布了这个问题,但是,我认为它过于复杂,我没有很好地解释它。这次我只是以一个简单的UserForm为例。

我想通过在文本框中输入搜索条件来填充ListBox。

我有三列:

A栏=图书馆卡号

B栏=学生姓名

C列=图书参考

我有一个UserForm:

TextBox = txtlcn(图书馆卡号)

TextBox = txtpn(对于学生姓名)

TextBox = txtbr(用于图书参考)

命令按钮= cmdfinddetails(查找详细信息)

我想要做的是将TextBox'txtbr'更改为ListBox,以便我可以看到学生是否有多本书借给他们。这个过程将是:

  1. 学生在TextBox'txtlcn'中输入他们的图书馆卡号 点击命令按钮'cmdfinddetails'
  2. 代码将搜索该Pupil的名称和所有书籍 预订的参考资料。
  3. 图书参考将显示在列表框中。
  4. 我尝试过很多与RowSource有关的事情,但它总是列出每个学生的书籍参考。以下是我的示例代码。

    Private Sub cmdfinddetails_Click()
    Set xSht = Sheets("Library")
            Lastrow = xSht.Range("A" & Rows.Count).End(xlUp).Row
            strSearch = txtlcn.Text
                        Set aCell = xSht.Range("A1:A" & Lastrow).Find
    
    (What:=strSearch, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)
    
          If Not aCell Is Nothing And txtpn.Value = "" Then
             GoTo libcardrefvalid      
         Else
    MsgBox "Oops! That Library Card does not exist. Please try again.", Title:="We LOVE Reading ;-)"
    txtlcn.Value = ""
            End If
        Exit Sub
    libcardrefvalid:
    
    row_number = 0
    Do
    DoEvents
    row_number = row_number + 1
    item_in_review = Sheets("Library").Range("A" & row_number)
    If item_in_review = txtlcn.Text Then
    txtpn.Text = Sheets("Library").Range("B" & row_number)
    txtbr.Text = Sheets("Library").Range("C" & row_number)
    End If
    Loop Until item_in_review = ""
    
    End Sub
    

    非常感谢任何帮助。

    谢谢。

1 个答案:

答案 0 :(得分:2)

假设您已将txtbr更改为列表框,我可以使用以下添加内容使您的代码正常工作(查找学生姓名并添加引用到txtbr列表框中的所有书籍):

Private Sub CommandButton1_Click()
'clears the pupil name (caused an error if not done)
txtpn.Text = ""
Set xSht = Sheets("Library")
        Lastrow = xSht.Range("A" & Rows.Count).End(xlUp).Row
        strSearch = txtlcn.Text
                    Set aCell = xSht.Range("A1:A" & Lastrow).Find(What:=strSearch, LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)

      If Not aCell Is Nothing And txtpn.Value = "" Then
         GoTo libcardrefvalid
     Else
MsgBox "Oops! That Library Card does not exist. Please try again.", Title:="We LOVE Reading ;-)"
txtlcn.Value = ""
        End If
    Exit Sub
libcardrefvalid:

row_number = 0
'clears the listbox so that you have dont have a continuously growing list
txtbr.Clear
Do
DoEvents
row_number = row_number + 1
item_in_review = Sheets("Library").Range("A" & row_number)
If item_in_review = txtlcn.Text Then
txtpn.Text = Sheets("Library").Range("B" & row_number)
'Adds the book reference number to the list box
txtbr.AddItem Sheets("Library").Range("C" & row_number)
End If
Loop Until item_in_review = ""
End Sub

我制作了一个测试用户表单和一些模拟数据,这对我有用。希望你也能发现它也适合你。