How to close a form without saving data

I have a search form that I want the user to close with a cancel button.  If data is entered I don't want it saved.  I have used the attached code, which works if there is data entered.  But when no data is entered I get a run time error.  How do I enable a user to close the form without saving data on the rare occasion that no data is entered?
Private Sub Cancel_Click()
    DoCmd.DoMenuItem acFormBar, acEditMenu, acUndo, , acMenuVer70
    DoCmd.Close acForm, Me.Name
End Sub

Open in new window

Harry BattDirector of DevelopmentAsked:
Who is Participating?
 
DatabaseMX (Joe Anderson - Microsoft Access MVP)Database ArchitectCommented:


Private Sub Cancel_Click()
    Me.Undo
    DoCmd.Close acForm, Me.Name
End Sub

Or

Private Sub Cancel_Click()
    On Error Resume Next
    Me.Undo
    Err.Clear
    DoCmd.Close acForm, Me.Name
End Sub

mx
0
 
DatabaseMX (Joe Anderson - Microsoft Access MVP)Database ArchitectCommented:
Note however, Undo only applies if data has been entered (Form is Dirty)... BUT ... the user wants to cancel that entry.  If no data has been entered, there is nothing to Undo.  

mx
0
 
Harry BattDirector of DevelopmentAuthor Commented:
DatabaseMX--I understand. So if there is nothing to undo, how do I close the form?  I have disabled the close button. I know it probably has to do with the dirty property, but don't know the proper syntax.  My goal is for the cancel button to work regardless if data has been entered.
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
peter57rCommented:
(no points)   You use the second option posted by mx

Or you can do:

If me.dirty then me.undo
DoCmd.Close acForm, Me.Name
0
 
Harry BattDirector of DevelopmentAuthor Commented:
DatabaseMX--Thanks again.  I apologize for not realizing that your comment after you posted the solution was referring to the first option and not both options.  I respect your amazing talent.
0
 
DatabaseMX (Joe Anderson - Microsoft Access MVP)Database ArchitectCommented:
Actually, the first solution works fine because Undo does not error if there is nothing to undo ... just wasn't sure last night.

" My goal is for the cancel button to work regardless if data has been entered."
Yes, that's what it does ... doubles as a close button if no data is entered.

thx for the kudos ...

mx
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.