【问题标题】:Search 2 criteria in ListBox in VBA Excel在 VBA Excel 的 ListBox 中搜索 2 个条件
【发布时间】:2019-01-20 06:15:32
【问题描述】:

我的代码:

Sub Search_Click()

Dim x1, i As Long, ii As Long, iii As Integer
x1 = [myCar]
Application.ScreenUpdating = False
With ListBox1
    If TextBox2 = "" Then
        .RowSource = "myCar"
    Else
        .RowSource = ""
        For i = 1 To UBound(x1, 1)
            If LCase(x1(i, 2)) Like LCase(TextBox2) & "*" Then 'Search location column 2

                For ii = 1 To 10
                    .AddItem
                    .List(iii, ii - 1) = x1(i, ii)
                Next
                iii = iii + 1
            End If
        Next
    End If
End With
End Sub

“搜索”是命令按钮

“myCar”是sheet1中A:J(10列)的名称范围,它是ListBox1中的RowSource

“TextBox2”用于输入搜索条件

当我打开 UserForm1 时,我有另一个代码将 RowSource("myCar") 同步到 ListBox1。之后,我可以在 ListBox1 填充后搜索数据。

上面的代码用于在 TextBox2 中使用单个条件搜索 ListBox1 中的数据。我的代码可以根据 RowSource("myCar") 中第 2 列中的条件搜索 ListBox1 中的数据

=> 我的问题:

我想用 2 个条件在 ListBox1(填充后)中搜索数据:

  1. TextBox2.value = 第一个条件,即 range("myCar") 中第 2 列中的数据

  2. TextBox3.value = 第二个条件,即 range("myCar") 中第 3 列中的数据

【问题讨论】:

    标签: excel vba search listbox


    【解决方案1】:

    如果您想根据两个(或更多)条件评估为真,其中所有条件都必须为真,您应该使用逻辑运算符 AND。取自https://www.excel-easy.com/vba/examples/logical-operators.html 的示例:

    Dim score1 As Integer, score2 As Integer, result As String
    
    score1 = Range("A1").Value
    score2 = Range("B1").Value
    
    If score1 >= 60 And score2 > 1 Then
        result = "pass"
    Else
        result = "fail"
    End If
    
    Range("C1").Value = result
    

    使用 AND 运算符修改您的 if 语句以包含另一个条件。

    【讨论】:

    • 感谢您的帮助,先生!如果 LCase(x1(i, 2)) Like LCase(TextBox2) & "" And LCase(x1(i, 2)) Like LCase(TextBox18) & "" 那么它不起作用。您的上述建议适用于“IF”的 2 个条件。如果我听从您的建议,我必须在数据来自 TextBox2.value 和 TexBox3.value 的范围内创建 1 列。我不想这样做。先生,您能建议另一种解决方案吗?
    • 提供一些带有数据的屏幕截图 - 这样会更容易获得解决方案。
    • 我在范围内有 10 列(“myCar”)。第 2 列是车型,第 3 列是产品年份。我想根据这两列的数据在 ListBox 中搜索数据
    • 先生?请帮助我
    • 点击帖子下方的编辑,然后点击左起第六个图标(带有一座山)。附上屏幕截图并更详细地解释您想要完成的内容。您可以使用虚拟数据简化您的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    • 2021-11-04
    • 2015-11-18
    • 2017-01-27
    • 1970-01-01
    • 2017-07-27
    相关资源
    最近更新 更多