rob
rob

Reputation: 3012

How to discard form content on application exit in MS Access?

How can I discard the content of a form when a user exits the application? If the user closes the form via button (e.g. to go back to the main form) this can be achieved with Me.Undo. But if he closes the whole application the current content is entered into the according table which is not as intended.
I also tried the on Close and on Unload events which are both not firing when the application is being closed.

edit: the on Close event shows strange behaviour. A MsgBox is being executed but the Me.Undo does somehow not work. (Maybe form content is being entered into the table before the event when the X is being clicked to exit the application?)

Upvotes: 1

Views: 2170

Answers (1)

HansUp
HansUp

Reputation: 97101

Closing a form automatically triggers save of pending changes to the values of bound controls. You can't intercept that save operation from the form unload or close events. And the only way I can find to intercept it at all is from the form's before update and insert events:

Dim SaveFlag As Boolean

Private Sub Form_BeforeUpdate(Cancel As Integer)
    If Me.Dirty = True And SaveFlag = False Then
        Me.Undo
    End If
End Sub

You would need to do similar for before insert. And you would need to manage SaveFlag somehow so that you could actually save changes when you want them saved.

Private Sub cmdSave_Click()
    SaveFlag = True
    Me.Dirty = False
    SaveFlag = False
End Sub

However, if you want Access' default behaviors such as automatically saving changes when navigating between records or when switching focus between a main and sub form, this approach is not suitable.

If you need this feature badly enough, you could switch to unbound data controls and only save their values when you explicitly order it to happen. But that would add a lot of extra work and I don't know if it's worth the effort. I would be tempted to treat this as a user education issue. "Be aware that if you close the application with unsaved changes in a form, the changes will be saved for you."

Upvotes: 1

Related Questions