Sabtu, 18 Maret 2017

Re: [MS_AccessPros] Form Error Handling

 

David-


OK, so you've implemented this code:

Private Sub Form_Error(DataErr As Integer, Response As Integer)
' This is standard code that I put in the Error event
' of all forms that edit data.  The idea is to try to intercept
' most of the common standard error messages - most of which are
' not user-friendly - and deal with them here.

    ' Pick options based on the error code - see ErrorTable for a complete list
    Select Case DataErr
        Case errCancel, errCancel2, errPropNotFound ' Cancel - ignore
            Response = acDataErrContinue
        Case errDuplicate  ' Duplicate row - custom error message
            MsgBox "You're trying to add a record that already exists.  " & _
                "Enter a new Company or click Cancel.", vbCritical, gstrAppTitle
            Response = acDataErrContinue
        Case errInvalid, errInputMask
            ' Invalid data - custom error and log
            MsgBox "You have entered an invalid value. ", vbCritical, gstrAppTitle
            ErrorLog Me.Name & "_Error", DataErr, AccessError(DataErr)
            Response = acDataErrContinue
        ' Field validation, Table validation, Custom Validation, End of Search, Spelling Check
        Case errValidation, errTableValidate, errCustomValidate, errSearchEnd, errSpellCheck
            ' Do nothing -- let the standard message display
            ' All validation rules in the tables have custom error messages.
            Response = acDataErrDisplay
        Case Else
            ' Dunno - log and let error display
            ErrorLog Me.Name & "_Error", DataErr, AccessError(DataErr)
            Response = acDataErrDisplay
    End Select
End Sub

Note that it specifically traps cancel errors (like setting Cancel = True in Before Update), duplicate rows, and a host of validation errors that can be triggered as the user enters data in fields that have input masks or validation rules.  It won't, for the most part, trap any other errors.  For those, you need a specific error trap in the code that might cause the error.  For example, I do all record saves from a common bit of code:

Private Function SaveIt() As Integer
Dim lngErr As Long, strError As String

    ' Common Save routine called from cmdSave and a couple of other places
    
    ' Default: We expect this to work
    SaveIt = True
    ' No need to do anything if the form isn't "dirty"
    If (Me.Dirty = True) Then
        ' OK, gonna try to save - set error trap
        On Error GoTo Save_Error
        Me.Dirty = False  ' Force a save by resetting Dirty
    End If
    
Save_Exit:
    Exit Function
    
Save_Error:
    ' Got here if the save failed.  Handle most common errors
    '  (Some may be handled by Form_Error instead)
    SaveIt = False  ' Indicate save failed
    ' Try to analyze the error
    Select Case Err
        Case errCancel, errCancel2, errPropNotFound ' Cancel - ignore
            Resume Save_Exit
        Case errDuplicate  ' Duplicate row - custom error message
            MsgBox "You're trying to add a record that already exists.  " & _
                "Enter a new Company or click Cancel.", vbCritical, gstrAppTitle
        Case errInvalid, errInputMask
            ' Invalid data - custom error and log
            MsgBox "You have entered an invalid value. ", vbCritical, gstrAppTitle
            ErrorLog Me.Name & "_Save", Err, Error
        ' Field validation, Table validation, Custom Validation, End of Search, Spelling Check
        Case errValidation, errTableValidate, errCustomValidate, errSearchEnd, errSpellCheck
            ' Display the error
            ' All validation rules in the tables have custom error messages.
            MsgBox Error, vbCritical, gstrAppTitle
        Case Else
            ' Dunno - log and let error display
            ' Save the error code values because ErrorLog may get additional errors
            lngErr = Err
            strError = Error
            ErrorLog Me.Name & "_Save", lngErr, strError
            MsgBox "Error attempting to save: " & lngErr & " " & strError & Chr$(13) & Chr$(10) & "Try again or click Cancel to close without saving.", 48, gstrAppTitle
    End Select
    Resume Save_Exit

End Function

Note that it sets its own error trap and does not depend on Form_Error being triggered.

For example, I call it from my Close button like this:

Private Sub cmdClose_Click()
    ' User wants to save any pending work and exit
    ' Call the common save routine - returns False if save failed
    If Not SaveIt() Then Exit Sub
    ' Close me
    DoCmd.Close acForm, Me.Name
End Sub

Also be sure that the form's On Error property is set to [Event Procedure].  If not, then the code will never run.

John Viescas, Author
Effective SQL
SQL Queries for Mere Mortals 
Microsoft Access 2010 Inside Out
Microsoft Access 2007 Inside Out
Microsoft Access 2003 Inside Out
Building Microsoft Access Applications 
(Paris, France)




On Mar 18, 2017, at 2:40 PM, david.pratt@outlook.com [MS_Access_Professionals] <MS_Access_Professionals@yahoogroups.com> wrote:



John, I added the Form_Error sub from your Contacts database to some of my forms attached to the form OnError event.  My form is not executing the sub when there is an error and I am not sure what I have to do.  Perhaps I have a misunderstanding of when a "form error occurs".

I have several forms where I have placed buttons for cmdSaveAndNew and cmdSaveAndClose.  I am intentionally adding duplicate records and my button errors are not calling your form_error sub. The duplicate records are not being saved, but there is no notification to the user. 

Private Sub cmdSaveAndNew_Click()
     If (Form.Dirty) Then
        DoCmd.RunCommand acCmdSaveRecord
        Forms!frmConfigureGroupsAndSamples.SetFocus 'return to the calling form
        Forms!frmConfigureGroupsAndSamples!lstSampleGroups.Requery 'update the list box
        Me.txtSampleGroupName.SetFocus  'return to this form and set focus to the Sample Group Name again
    End If

    DoCmd.GoToRecord , "", acNewRec
    DoCmd.GoToControl "txtSampleGroupName"
End Sub


Private Sub cmdSaveAndClose_Click()
    If (Form.Dirty) Then
        DoCmd.RunCommand acCmdSaveRecord

        Forms!frmConfigureGroupsAndSamples.SetFocus 'return to the calling form
        Forms!frmConfigureGroupsAndSamples!lstSampleGroups.Requery 'update the list box
        Me.txtSampleGroupName.SetFocus  'return to this form and set focus to the Sample Group Name again
    End If

    DoCmd.Close , ""


Do I have to add your CASE statement to each of these button events?





__._,_.___

Posted by: John Viescas <johnv@msn.com>
Reply via web post Reply to sender Reply to group Start a New Topic Messages in this topic (2)

Have you tried the highest rated email app?
With 4.5 stars in iTunes, the Yahoo Mail app is the highest rated email app on the market. What are you waiting for? Now you can access all your inboxes (Gmail, Outlook, AOL and more) in one place. Never delete an email again with 1000GB of free cloud storage.


.

__,_._,___

Tidak ada komentar:

Posting Komentar