【问题标题】:Form with multi-criteria searches - uses strings and filters具有多条件搜索的表单 - 使用字符串和过滤器
【发布时间】:2014-01-23 19:15:45
【问题描述】:

我有一个搜索表单,其中包含与表格关联的空白字段、四个条件搜索框和一个按钮,用于从搜索框中获取输入、搜索表格并在表格的空白字段中填充结果。

到目前为止,只要所有四个条件框都不为空,它就可以工作。
我使用过滤器来实现这一点,只要所有四个框都不为空,这里的代码就可以工作。 (我的标准框如下:一个名为“关键字”的文本框和三个名为 HRCombo、BuildingCombo 和 RoomCombo 的组合框,它们关联的字段如下:“项目描述”“人力资源持有人”“建筑”“ Room") 我的第一行“Me.Filter = ...”被拆分,以便于查看。

Me.Filter = "[Item Description] Like " & Chr(34) & Me.Keyword & "*" & Chr(34) & "
 AND [HR Holder] = '" & Me.HRCombo & "'" & " AND [Building] = '" & Me.BuildingCombo
 & "'" & " AND [Room] = '" & Me.RoomCombo & "'"
Me.FilterOn = True
Me.Requery

无论输入了哪种标准框组合,我都需要它能够进行搜索。有人建议使用 if 语句来执行以下操作: 创建四个字符串,每个条件框一个。使用 4 个 if 语句来检查框是否为空 - 如果为空,则为其字符串分配一个星号,如果它不为空,则将我用于上述 Me.Filter 语句的值分配给每个框的字符串。然后,使用 Me.Filter 并在最后连接四个字符串。

这是我用于此目的的代码,但以我的知识有限,我无法让它工作。

Dim StrA as String, StrB as String, StrC as String, StrD as String

If Me.Keyword is null then
StrA = "*"
else
StrA = [Item Description] Like " & Chr(34) & Me.Keyword & "*" & Chr(34)
End If

If Me.HRCombo is null then
StrB = "*"
else
StrB = [HR Holder] = '" & Me.HRCombo & "'"
End If

If Me.BuildingCombo is null then
StrC = "*"
else
StrC = [Building] = '" & Me.BuildingCombo & "'"
End If

If Me.RoomCombo is null then
StrD = "*"
else
StrD = [Room] = '" & Me.RoomCombo & "'"
End If

Me.Filter = "StrA & " AND "StrB & " AND "StrC &" AND "StrD"
Me.FilterOn = True
Me.Requery

就像我说的那样,我的知识有限,所以我确定可能缺少引号和逗号,或者太多了。有什么想法吗?

【问题讨论】:

    标签: vba forms ms-access


    【解决方案1】:

    您缺少一些重要的引号,并且您检查 null 的逻辑对于 SQL 是正确的,但对于 VBA 是不正确的。我在这里发布我认为是一种更清洁的方法。请注意,您没有转义可能在您的控件中输入的单引号,我也没有在此代码中(除了第一个,只是为了您可以看到如何使用 Replace 函数执行此操作)。每当单引号可能出现在其中一个搜索/过滤控件中时,这都是一件非常重要的事情。

    Dim strWhere as String
    
    If Nz(Me.Keyword, "") <> "" Then
        strWhere = strWhere & "[Item Description] Like '*" & Replace(Me.Keyword, "'", "''") & "*' AND "
    End If
    
    If Nz(Me.HRCombo, "") <> "" Then
        strWhere = strWhere & "[HR Holder] = '" & Me.HRCombo & "' AND "
    End If
    
    If Nz(Me.BuildingCombo, "") <> "" Then
        strWhere = strWhere & "[Building] = '" & Me.BuildingCombo & "' AND "
    End If
    
    If Nz(Me.RoomCombo, "") <> "" Then
        strWhere = strWhere & "[Room] = '" & Me.RoomCombo & "' AND "
    End If
    
    If strWhere <> "" Then
        strWhere = Left(strWhere, Len(strWhere)-5) 'Remove the extra AND
        Me.Filter = strWhere
        Me.FilterOn = True
    Else
        Me.Filter = ""
        Me.FilterOn = False
    End If
    

    【讨论】:

    • 太棒了!感谢您的帮助!
    • 另一个问题...第一个 strWhere 语句的末尾有一个星号...我最初用它来告诉在字段中查找具有用户键入关键字的任何内容,但是它只显示关键字是该字段中第一个单词的结果。之前也是这样做的。所以我的问题是如何在开头添加一个星号,以便访问将查找其中包含关键字的任何字段。基本上,如果它处于查询模式,它将是......就像 * & 关键字 & * 我无法弄清楚如何以正确的方式得到它......爆破引号和双引号 :)
    • 我已将星号添加到开头,以便您查看它的外观。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2013-12-17
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    相关资源
    最近更新 更多