MS Access错误捕获

时间:2013-12-26 11:45:13

标签: ms-access

拜托,我的逻辑能力有限。

搜索条件的文本框和SEARCH按钮位于主窗体上,而搜索结果位于弹出窗体上。

如果提供的条件与数据库中的任何记录不匹配,我不希望打开详细信息表单。相反,我希望弹出错误消息“抱歉,没有搜索条件”,但在我当前状态下,当没有匹配结果/没有条件时,详细信息表单仍会打开,其中包含一些记录和错误消息。

以下是SEARCH按钮背后的代码:

Private Sub btnSearch_Click()
On Error GoTo Err_Msg

If Not IsNull(Me.Form) Then

    DoCmd.OpenForm "f_search"
    ' Update the record source
    Forms.f_search!f_search_sub.Form.RecordSource = "SELECT * FROM q_vehicles " & BuildFilter

    Me.Requery
Else

Exit_btnSearch_Click:
Exit Sub

Err_Msg:
MsgBox "Sorry, no search criteria.", vbInformation, "MV Clearance"
End If
End Sub

1 个答案:

答案 0 :(得分:1)

您可以轻松搜索第一个,然后仅在该搜索返回结果时才打开表单:

Private Sub btnSearch_Click()
Dim rec as Recordset
Dim db as Database
On Error GoTo Err_Msg

Set db = CurrentDB

If Not IsNull(Me.Form) Then
    'First open the recordset
    Set rec = db.OpenRecordset("SELECT * FROM q_vehicles " & BuildFilter & "")

    'Check to make sure the recordset isn't empty.  If it is, exit the sub
    If rec.EOF = true then
        GoTo Err_Msg
    EndIf

    DoCmd.OpenForm "f_search"
    ' Update the record source
    Forms.f_search!f_search_sub.Form.RecordSource = "SELECT * FROM q_vehicles " & BuildFilter

    Me.Requery
Else

Exit_btnSearch_Click:
    Set db = Nothing
    Set rec = Nothing
Exit Sub

Err_Msg:
MsgBox "Sorry, no search criteria.", vbInformation, "MV Clearance"
End If
GoTo Exit_btnSearch_Click
End Sub