vba to cancel close even in a message box

musclecarlover07

Registered User.
Local time
Today, 13:05
Joined
May 4, 2012
Messages
236
I have a form that if there is a change made to the field it puts the caption to Edited. If the user clicks the close button and the caption says "Edited" I want a message box to come up asking if the user wants to continue and lose any unsaved issues. If they select yes then it closes the form. If they select no I want it to cancel the event an keep the form open.

Below is the code that I have. I have used the DoCmd.CancelEvent on another instance but it wasn't used in a message box. Is there another way around this?

Code:
Dim MakeChange As String

    If Form.Caption = "Edited" Then
        MakeChange = MsgBox("There are unsaved changes. Do you still wish to exit?", vbCritical + vbYesNo)
        If MakeChange = vbYes Then
            
            MsgBox "Changes were not saved and were reverted back.", vbOKOnly
        ElseIf MakeChange = vbNo Then
            Docmd.CancelEvent
        End If
    End If
 
Perhaps a bit longwinded. You could use the form's .Dirty property.

Code:
If Me.Dirty Then
    If MsgBox("Save changes?", vbYesNo, "Form Edited") = vbYes Then
        DoCmd.RunCommand acCmdSaveRecord
    Else
        Me.Undo
    End If
End If

Or:

Code:
If Me.Dirty Then
    If MsgBox("Save changes?", vbYesNo, "Form Edited") = vbNo Then
        Me.Undo
        MsgBox "Changes reverted", vbInformation
    End If
End If
 
Awesome! That worked perfectly. Just with a few slight modifications It will be perfect. Thank you for that and the quick response :)
 

Users who are viewing this thread

Back
Top Bottom