2017-02-14 72 views
1

解決方案訪問輸入表單與自定義錯誤消息

解決的辦法是不要嘗試,並捕獲錯誤,但這樣做的錯誤處理自己爲添加記錄命令按鈕的一部分:

Private Sub buttonNewRecord_Click() 

Dim ErrorInt As Integer 
Dim TeleCheck As Variant 

Name.SetFocus 
If Name.Text = "" Then 
MsgBox "Name is missing!" 
ErrorInt = ErrorInt + 1 
End If 

TeleCheck = DLookup("[Telephone]", "tblColdCallLog", "[Telephone] = '" & Me.Telephone & "'") 
If Not IsNull(TeleCheck) Then 
MsgBox "Telephone number already exists in the table!" 
ErrorInt = ErrorInt + 1 
End If 

If ErrorInt < 1 Then 
DoCmd.GoToRecord , , acNewRec 
MsgBox "Record Added!" 
End If 

End Sub 

原貼:

我擁有的一切:

我有ç重新使用一個簡單的Access 2013 Form來將數據輸入到表中。在窗體上,用戶將數據輸入到字段中,然後單擊使用「命令按鈕嚮導」創建的按鈕以添加新記錄。

表單有一個必填字段[Name]和一個字段設置爲'Index:Yes(No Duplicates)',[Telephone Number]。在表單中,如果[名稱]字段爲空或在[電話]字段中檢測到重複號碼,則表格中也會正確生成錯誤消息。

我所試圖做的事:

出現的錯誤消息是不是用戶友好的。我想用自定義錯誤信息替換它們,如果沒有錯誤,可能會有一條消息說明一切順利。

我曾嘗試什麼:

在窗體屬性,事件選項卡,在「上的錯誤」,[事件過程]:

Private Sub Error_Sub(DataErr As Integer, Response As Integer) 
    If DataErr = 3022 Then 
    MsgBox "Duplicate telephone number found in table!" 
    Response = acDataErrContinue 
    End If 
    If DataErr = 3314 Then 
    MsgBox "Name is missing!" 
    Response = acDataErrContinue 
    End If 
End Sub 

這工作,但只有當你關閉窗體...當您點擊「添加新記錄」命令按鈕時,它會在適當的時候顯示默認的錯誤消息。

也許我應該使用「更新前的事件」?我似乎無法使用相同的VBA腳本。我不允許定義DataErr或Response。所以,我將使用一個表達式來代替:

=IIf(Error(3022),MsgBox("Duplicate telephone number found in table")) 
=IIf(Error(3314),MsgBox("Name is missing")) 

這可以工作......但是當沒有錯誤時。即使在[名稱]字段中有名稱,也會顯示錯誤,但至少會替換默認錯誤消息。

讓我們把它放在按鈕本身?我將不得不使用宏生成器來編輯它。複製和粘貼這個有點難,所以我會簡化:

OnError GoTo Error_Handling 
GoToRecord New 
If [MacroError]<>0 Then 
    MsgBox = "[MacroError].[Description]" 
End If 

Error_Handling: 
If Error(3022) Then 
    MsgBox = "Duplicate telephone number found in table!" 
End If 
If Error(3314) Then 
    MsgBox = "Name is missing!" 
End If 

這和'Before Update'事件一樣;替換默認的錯誤消息,但不管錯誤消息是否應該首先觸發。

我在做什麼錯?我感覺這很簡單。我嘗試了各種其他組合和無盡的谷歌搜索,但我感到困惑。

+1

添加記錄時,我幾乎總是使用未綁定的表單並在運行帶有參數的更新查詢之前檢查每個必需的控件(字段)。這是可擴展的。 – Fionnuala

+1

最好的選擇是防止輸入錯誤。在窗體的BeforeUpdate事件中或在可能的情況下在單獨控件的Before-或AfterUpdate事件中執行此操作。然後讓表單的錯誤處理來處理其他錯誤,通常是那些不受用戶控制的錯誤。 – Gustav

+0

謝謝。古斯塔夫讓我走上正軌。我沒有試圖捕捉錯誤,而是將錯誤處理作爲「添加新記錄」按鈕的一部分。解決方案添加到OP。 – ETP

回答

0
Private Sub buttonNewRecord_Click() 

Dim ErrorInt As Integer 
Dim TeleCheck As Variant 

Name.SetFocus 
If Name.Text = "" Then 
MsgBox "Name is missing!" 
ErrorInt = ErrorInt + 1 
End If 

TeleCheck = DLookup("[Telephone]", "tblColdCallLog", "[Telephone] = '" & Me.Telephone & "'") 
If Not IsNull(TeleCheck) Then 
MsgBox "Telephone number already exists in the table!" 
ErrorInt = ErrorInt + 1 
End If 

If ErrorInt < 1 Then 
DoCmd.GoToRecord , , acNewRec 
MsgBox "Record Added!" 
End If 

End Sub