VBA Code for Exit Command Button

wilderfan

Registered User.
Local time
Yesterday, 21:02
Joined
Mar 3, 2008
Messages
172
The form I am working on allows users to change the name of an existing corporation and record the date of the name change.

The form has 2 command buttons. The first button verifies the date and closes the form (as long as the date is valid). The second button allows the user to abort the name change and exit the form.

When exiting the form, I can't just delete the last record in the table because there might be occasions where the user accidentally goes into the form and wants to exit immediately without entering a new record.

QUESTION: Is it possible to build some sort of "If" structure into the VBA code of the Exit command button so that deletion of the last record occurs ONLY when a new record has truly been added?

I suppose I could use 2 Exit command buttons: Click Exit Button 1 if you did NOT try to enter a new record; and Click Exit Button 2 if you DID try to enter a new record and decided NOT to keep it.

But this seems very cumbersome. Any suggestions?
 
At the time the user presses the button, the current record has not yet been saved so there is no need to delete it. You just have to prevent it from being saved.

Define a module level boolean variable for the form.
In the form's current event, set the variable to False.
In the first button, set the value of the variable to True (yes I want to save).
In the form's BeforeUpdate event, add code to check the value of the variable and if the user has not pressed the save button, the variable will be false.

If bSaveRecord = True Then
Else
Cancel = True
Me.Undo
Exit Sub
End if

In the second button, you need to undo the update before you close the form.

Me.Undo
docmd.close

You can add message boxes to prompt the user if you want to give him a second chance in either of the options.
 
Thanks, Pat.

I seem to be getting a compile error on the Current Event of the Form.

The message says "Object Required".

I've attached a Word document to show you the code (with changes noted in bold red).

If you can spot where I've gone wrong, please let me know.

Thanks.


-- Robert
 

Attachments

Users who are viewing this thread

Back
Top Bottom