2015-04-07 21 views
0

我正在使用MS Access 2007編寫一個小型數據庫。我在其中有一個用於運行查詢和打印報告的功能。如果給出多個查詢條件中的任何一個,則打印工作得很好。在MS Access中沒有給出查詢條件時捕獲錯誤

如果用戶在沒有查詢條件的情況下單擊「打印」按鈕,我還想要捕獲錯誤並顯示一條消息。目前,我只能得到一個運行時語法錯誤消息,它有一個用於訪問整個代碼的「調試」按鈕。我想要一個消息,會說「對不起,沒有搜索條件」。

這是打印的代碼:

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 
+0

[在VBA錯誤處理(HTTP:// WWW。 cpearson.com/excel/errorhandling.htm) –

回答

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