在MS Access中未给出查询条件时捕获错误

时间:2015-04-07 08:56:31

标签: ms-access-2007

我正在使用MS Access 2007编写一个小型数据库。我在其中有一个运行查询和打印报告的功能。如果给出多个查询条件中的任何一个,则打印工作正常。

如果用户在没有查询条件的情况下单击“打印”按钮,我还想捕获错误并显示消息。目前我只得到一个运行时语法错误消息,它有一个“调试”按钮,用于访问整个代码。我想要一条消息,说“抱歉,没有搜索条件”。

这是打印代码:

Private Sub cmdPrint_Click()
Dim varWhere As Variant
    varWhere = BuildFilter

    ' Update the record source
    Me.RecordSource = "SELECT * FROM q_Vehicles " & varWhere

    ' Requery the form
    Me.Requery

    ' Check if there is a filter to return...
    If IsNull(varWhere) Then
        varWhere = ""
    Else
    'The WHERE clause does NOT need the word "WHERE"

        ' strip off "WHERE " in the filter
        varWhere = Mid(varWhere, 7)
    End If

DoCmd.OpenReport "rpt_Vehicles", acPreview, , varWhere
End Sub

1 个答案:

答案 0 :(得分:0)

就像快速解决它一样。您有两个选项您可以在没有条件的情况下打开报告,也可以在打开之前让报告请求标准。请记住,我不知道BuildFilter返回什么,因此varWhere可能永远不会为null,在这种情况下需要修改代码。如果您有任何问题,请告诉我。

如果列出了标准,则只打开报告:

    Private Sub cmdPrint_Click()
    Dim varWhere As Variant
        varWhere = BuildFilter

If isnull(varWhere) Then ' Check if null
  Msgbox "Sorry, there was no search criteria" ' Msgbox opens then stops code
Exit Sub ' Stop the code from running
End if

        ' Update the record source
        Me.RecordSource = "SELECT * FROM q_Vehicles " & varWhere

        ' Requery the form
        Me.Requery

        ' Check if there is a filter to return...
' This was already checked above so is not necessary anymore
'        If IsNull(varWhere) Then
'            varWhere = ""
'        Else
        'The WHERE clause does NOT need the word "WHERE"

            ' strip off "WHERE " in the filter
            varWhere = Mid(varWhere, 7)
'        End If

    DoCmd.OpenReport "rpt_Vehicles", acPreview, , varWhere
    End Sub

让它以任何方式打开:

Private Sub cmdPrint_Click()
Dim varWhere As Variant
    varWhere = BuildFilter

    ' Update the record source
    Me.RecordSource = "SELECT * FROM q_Vehicles " & varWhere

    ' Requery the form
    Me.Requery

    ' Check if there is a filter to return...
    If IsNull(varWhere) Then
        DoCmd.OpenReport "rpt_Vehicles", acPreview ' Open form directly if no filter is supplied

    Else
    'The WHERE clause does NOT need the word "WHERE"

        ' strip off "WHERE " in the filter
        varWhere = Mid(varWhere, 7)
        DoCmd.OpenReport "rpt_Vehicles", acPreview, , varWhere ' Open with criteria
    End If


End Sub