當表單具有焦點時,在 Microsoft Access 中產生執行階段錯誤時,就會發生 Error 事件。
語法
表達。DataErr (錯誤,回應)
expression 代表 Form 物件的變數。
參數
| 名稱 | 必要/選用 | 資料類型 | 描述 |
|---|---|---|---|
| DataErr | 必要 | 整數 | 發生錯誤時 Err 物件所傳回的錯誤碼。 將 DataErr 引數與 Error 函數搭配使用,將數字對應至對應的錯誤訊息。 |
| 回應 | 必要 | 整數 | 此設定會決定是否顯示錯誤訊息。
Response 引數可以是下列內建常數的其中之一。
|
註解
這包括 Access 資料庫引擎錯誤,但不包括 Visual Basic 中的執行階段錯誤或來自 ADO 的錯誤。
若要在發生此事件時執行巨集或事件程序,請將 OnError 屬性設定為巨集名稱或 [事件程序]。
藉由在發生 錯誤 事件時執行事件程式或巨集,您可以攔截 Access 錯誤訊息,並顯示自訂訊息,以傳達應用程式更具體的意義。
範例
下列範例顯示如何以自訂的錯誤訊息取代預設的錯誤訊息。 當 Access 傳回錯誤訊息,指出它已找到重複的金鑰 (錯誤碼 3022) 時,此事件程式會顯示一則訊息,為使用者提供更多應用程式特定資訊。
若要嘗試此範例,請在以具有唯一員工編號作為每筆記錄索引鍵的資料表為基礎的表單上新增下列事件程序。
Private Sub Form_Error(DataErr As Integer, Response As Integer)
Const conDuplicateKey = 3022
Dim strMsg As String
If DataErr = conDuplicateKey Then
Response = acDataErrContinue
strMsg = "Each employee record must have a unique " _
& "employee ID number. Please recheck your data."
MsgBox strMsg
End If
End Sub
下列範例顯示如何以自訂的錯誤訊息取代預設的錯誤訊息。
Private Sub Form_Error(DataErr As Integer, Response As Integer)
Select Case DataErr
Case 2113
MsgBox "Only numbers are acceptable in this box", vbCritical, "Call 1-800-123-4567"
Response = acDataErrContinue
Case 2237
MsgBox "You can only choose from the dropdown box"
Response = acDataErrContinue
Case 3022
MsgBox "You entered a value that exists already in another record"
Response = acDataErrContinue
SSN.Value = SSN.OldValue
Case 3314
MsgBox "The DOH is required, so you cannot leave this field empty"
Response = acDataErrContinue
Case Else
Response = acDataErrDisplay
End Select
ActiveControl.Undo
End Sub
支援和意見反應
有關於 Office VBA 或這份文件的問題或意見反應嗎? 如需取得支援服務並提供意見反應的相關指導,請參閱 Office VBA 支援與意見反應。