2012-12-02 42 views
2

在Access 2007年,我有一個表格到一個新的聯繫人添加到一個表:的MessageBox如果記錄更新成功

RecSet.AddNew 
RecSet![Code_Personal] = Me.txtCodePersonal.Value 
RecSet![FName] = Me.TxtFName.Value 
RecSet![LName] = Me.txtLName.Value 
RecSet![Tel Natel] = Me.txtNatTel.Value 
RecSet![Tel Home] = Me.txtHomeTel.Value 
RecSet![Email] = Me.txtEmail.Value 
RecSet.Update 

這在目前的工作,接觸已成功交鋒。但我有兩個問題:我想顯示一個消息框,告訴接觸已成功添加

  • 用戶如果沒有成功添加聯繫人

    1. 因爲
      1. 名稱已經接觸存在
      2. 不同的問題
        然後分別顯示一個消息框「聯繫已存在」或「錯誤發生」。

    我這樣做的想法是:

    If recSet.Update = true Then 
    MsgBox "Paolo Bernasconi was successfully added" 
    Else if RecSet![FName] & RecSet![LName] 'already exist in table 
    MsgBox "Contact already exists" 
    Else 
    MsgBox "An unknown error occured" 
    

    我知道這個代碼是錯誤的,顯然是行不通的,但它只是給你的,我有什麼想法試圖實現。感謝您提前提供的所有幫助。

  • 回答

    1

    將錯誤處理程序添加到您的過程。

    On Error GoTo ErrorHandler 
    

    然後在更新記錄集後立即向用戶顯示「成功」通知。

    RecSet.Update 
    MsgBox RecSet![FName] & " " & RecSet![FName] & _ 
        " was successfully added" 
    

    如果更新嘗試失敗,流量控制將傳遞到ErrorHandler部分。

    ErrorHandler: 
        MsgBox "Oops!" 
    

    毫無疑問,你想要的東西比「哎呀!」更精緻。信息。一種巧妙的方法是使用Select Case塊來根據錯誤編號自定義響應。

    在嘗試添加聯繫人之前,確定聯繫人是否已存在。

    strCriteria = "Fname = '" & RecSet![FName] & "' AND LName = '" & _ 
        RecSet![LName] & "'" 
    Debug.Print strCriteria 
    If DCount("*", "YourTable", strCriteria) > 0 Then 
        ' do not attempt to add it again 
        MsgBox "Contact already exists" 
    Else 
        RecSet.AddNew 
        ' and so forth 
    End If 
    

    檢查,以防Debug.Print輸出I構建strCriteria時犯了一個錯誤。

    此處的意圖是通過僅嘗試添加不存在的聯繫人來避免重複錯誤情況。所以錯誤不應該發生,任何錯誤將由錯誤處理程序處理。