【问题标题】:How to filter a form with multi-Field in MS Access using VBA如何使用 VBA 在 MS Access 中过滤具有多字段的表单
【发布时间】:2015-05-09 21:31:16
【问题描述】:

我在 MS Access 2013 表单中的单击按钮事件中有以下代码,其数据源来自具有以下字段“EnrNo、FirstName、LastName 和 RegDate”的查询。

表单有三个文本框和一个命令按钮:

  1. txt关键字
  2. txtDateFrom
  3. txtDateTo
  4. cmdSearch

表单中的单击按钮 (cmdSearch) 旨在根据三个条件过滤查询,这些条件可以是两个“EnrNo、FirstName、LastName”和文本中输入的日期范围中的任何一个框 txtDateTo 和 cmdSearch

我的代码仅成功过滤了 EnrNo。请帮帮我...感谢您的宝贵时间。

Private Sub cmdSearch_Click()
Dim strWhere As String                  'The criteria string.
Dim Where As String
Dim lngLen As Long                      'Length of the criteria string   to append to.
Const conJetDate = "\#mm\/dd\/yyyy\#"   'The format expected for dates in a JET query string.

'Text field example. Use quotes around the value in the string.
If Not IsNull(Me.txtFilter) Then
strWhere = strWhere & "([EnrNo] = """ & Me.txtFilter & """) OR "
strWhere = strWhere & "([FirstName] = """ & Me.txtFilter & """) AND "
End If

'Date field example. Use the format string to add the # delimiters and get the right international format.
If Not IsNull(Me.txtFrom) Then
strWhere = strWhere & "([RegDate] >= " & Format(Me.txtFrom, conJetDate) & ") AND "
End If

'Another date field example. Use "less than the next day" since this field has times as well as dates.
If Not IsNull(Me.txtTo) Then   'Less than the next day.
strWhere = strWhere & "[RegDate] BETWEEN #" & Format(Me.txtFrom, "mm/dd/yyyy") & "# AND #" & Format(Me.txtTo, "mm/dd/yyyy") & "# "
End If

lngLen = Len(strWhere) - 5
If lngLen <= 0 Then     'Nah: there was nothing in the string.
    MsgBox "No criteria", vbInformation, "Nothing to do."
Else                    'Yep: there is something there, so remove the "  AND " at the end.
    strWhere = Left$(strWhere, lngLen)
  'Debug.Print strWhere

Me.Filter = strWhere
Me.FilterOn = True
End If
End Sub

【问题讨论】:

  • 你可以粘贴或调试。一旦填充了过滤器,请打印整个 sql 过滤器?更容易告诉你问题是什么,我怀疑它的东西没有正确括起来
  • 它显示“运行时错误 '3075': 查询表达式中的数据语法错误 '([EnrNo] = “MS-12/IT-004”) 或 ([FirstName] = “MS -12/IT-004”) AND ([RegDate] >= #06/16/2014#) AND [RegDate] BETWEEN #06/16/2014# AND #09/23/2'

标签: ms-access vba


【解决方案1】:

它显示“运行时错误'3075':查询表达式中的数据语法错误'([EnrNo] = “MS-12/IT-004”)或([FirstName] = “MS-12/IT- 004”) AND ([RegDate] >= #06/16/2014#) AND [RegDate] BETWEEN #06/16/2014# AND #09/23/2' 你这里的操作数太多了。

您需要这样做,以便查询的 where 语句如下所示;

(([EnrNo] = “MS-12/IT-004”) or ([FirstName] = “MS-12/IT-004”)) AND (([RegDate] >= #06/16/2014#) AND ([RegDate] BETWEEN #06/16/2014# AND #09/23/2014#))

请注意我在其中放置的额外括号。逻辑运算符 (OR/AND) 将根据两个表达式返回一个值。例如,如果两个条件都为真,则 a > b AND b > c 返回真。如果任一语句为真,则 a > b OR b > c 返回真。

如果我们写一个像 a > b 和 b > c 或 d > f 这样的语句,我们有太多的条件,所以我们需要嵌套它们。所以我们将其写为 (a > b AND b > c) OR d > f。

实践这一点的一个好方法是在查询构建器中手动创建带有条件的查询,然后在查询的 SQL 视图窗口中查看放置在条件上的括号。

我希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2014-05-15
    • 1970-01-01
    • 2016-01-04
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    相关资源
    最近更新 更多