【问题标题】:Search by textbox and display in listbox按文本框搜索并显示在列表框中
【发布时间】:2018-03-13 06:14:31
【问题描述】:

我正在尝试创建将在列表框中显示信息的搜索。

我正在尝试按名称和日期范围、或按名称或仅按日期进行搜索。

我有代码,日期是正确的,但它显示了所有的名字。

Private Sub cmdFind_Click() 

    Dim DateRange As Range, rCl As Range, rng As Range, Dn As Range 
    Dim Date1 As Date, Date2 As Date 
    Dim iX As Integer 
    Dim strName As String 

    Set DateRange = Sheet2.Range("A1").CurrentRegion.Columns(4) 
    Set rng = Sheet2.Range("A1").CurrentRegion.Columns(4) 
    Me.ListBox1.Clear 

    strName = Me.txtName.Text 
    Date1 = CDate(Me.txtDate.Value) 
    Date2 = CDate(Me.EndDate.Value) 

    For Each rCl In DateRange.Cells 
        For Each Dn In rng.Cells 
            If rCl.Value >= Date1 And rCl.Value <= Date2 And strName Then

            ElseIf Dn.Value = strName Then 

                With Me.ListBox1 
                    .AddItem Sheet2.Cells(rCl.Row, 1) 
                    .List(.ListCount - 1, 1) = Sheet2.Cells(rCl.Row, 2) 
                    .List(.ListCount - 1, 2) = Sheet2.Cells(rCl.Row, 3) 
                    .List(.ListCount - 1, 3) = Sheet2.Cells(rCl.Row, 4) 
                    .List(.ListCount - 1, 4) = Sheet2.Cells(rCl.Row, 5) 
                    .List(.ListCount - 1, 5) = Format(Sheet2.Cells(rCl.Row, 6), "hh:mm:ss") 
                End With 
            End If 
        Next Dn 
    Next rCl 
End Sub

【问题讨论】:

  • 你有你的条件If rCl.Value &gt;= Date1 And rCl.Value &lt;= Date2 And Dn.Value = strName Then 并且不做这些动作,当名字匹配你添加它时,你正在添加所有东西。你应该删除这行ElseIf Dn.Value = strName Then
  • 嗨,我已经尝试删除语句 ElseIf Dn.Value = strName Then - 它仍然显示所有内容,然后例如我只使用名称过滤我收到 cdate 错误,因为没有价值。
  • 你循环两次相同的 Range For Each Dn In rng.CellsFor Each rCl In DateRange.Cells 因为 DataRange 和 rng 是相同的。虽然解决不了问题。
  • 如果我错了,请纠正我。我现在应该删除 -For Each Dn In rng.Cells- 并设置 rng = Sheet2.Range("A1").CurrentRegion.Columns(4) -。我对吗?对不起。我还是 VBA 新手,正在努力学习。
  • 你能举出你的数据表的例子吗?因为有些事情是不对的,比如Set rng = Sheet2.Range("A1").CurrentRegion.Columns(4)是D列,你用它来查找日期和字符串名称

标签: excel vba filter listbox userform


【解决方案1】:

假设您仅在同一行中检查日期范围:删除第二个循环 For Each Dn in rng.Cells 以及 Next Dn) 并将以下条件替换为:

        If (rCl.Value >= Date1 And rCl.Value <= Date2) And rCl.Offset(0, -3).Value = strName Then

顺便说一句,使用数组比使用范围循环更好。

【讨论】:

  • 嗨,我会试试这个。抱歉回复晚了。
猜你喜欢
  • 2015-12-16
  • 2019-09-22
  • 2019-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多