如何使用VBA

时间:2015-05-09 21:31:17

标签: access-vba

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

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

  1. txtKeyword
  2. txtDateFrom
  3. txtDateTo
  4. cmdSearch
  5. 表单中的单击按钮(cmdSearch)旨在根据三个条件筛选查询,这三个条件可以是两个“EnrNo,FirstName,LastName”中的任何一个以及在文本中输入的日期范围box 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
    

1 个答案:

答案 0 :(得分:0)

显示“运行时错误'3075':查询表达式中的数据中的语法错误'([EnrNo] =”MS-12 / IT-004“)或([FirstName] =”MS-12 / IT- 004“)AND([RegDate]&gt; =#06/16/2014#)和[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)将返回基于TWO表达式的值。例如,a>&gt; b和b>如果BOTH条件为真,则c返回true。 a&gt; b OR b>如果EITHER语句为真,则c返回true。

如果我们写一个类似&gt;的语句b和b> c或d>如果条件太多,我们需要嵌套它们。所以我们将其写成(a> b和b&gt; c)或者d&gt; F。

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

我希望这有帮助!