简体   繁体   中英

Form button to Save Record Clashing with Table Validation

I have a form which is intended for Data Entry, and a button which (should) save the record to the data table (ie goes to the next blank record) with a message box appearing saying "your record has been saved successfully".

However, I have mandatory fields on the form, where the validation is set in the data table to 'Is Not Null' so I am able to define the error messages which appear. This then causes, on the 'Save Record' button click, 1st: a messagebox appearing telling me it has saved successfully, followed by the Validation error message set in the data table, followed by "you can't go to the specified record", followed by the Macro Single Step window prompting me to 'Stop All Macros' How can I get the macro to stop running if a validation rule (set in the data table) fails? - I'd assume this would then go on the first event of the macro builder?

Thanks for any help provided!

You could do something like this, use this code as event procedure for your button.

Private Sub cmdSaveRecord_Click()

    ' Try to save the record, skip error
    On Error Resume Next
    DoCmd.RunCommand acCmdSaveRecord
    ' If not successful, display error and exit
    If Err.Number <> 0 Then
        ' Err.Description contains the field validation rule message
        MsgBox Err.Description, vbExclamation, "Error on saving"
        Exit Sub
    End If

    On Error GoTo 0

    MsgBox "Your record has been saved successfully", vbInformation
    ' new record
    DoCmd.GoToRecord acActiveDataObject, , acNewRec
    ' goto first control on new record, instead of cmdSaveRecord
    Me.Text1.SetFocus

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM