LuckyLuke82
LuckyLuke82

Reputation: 604

Access VBA - prevent closing form

I have a code in Before_Update event, for saving changes. For this I use Msgbox with YesNoCancel prompt, but I cannot prevent closing form when I hit Cancel button. Here is a short sample of my code:

Option Compare Database
Public SomeVariable As Integer

    Private Sub Form_BeforeUpdate(Cancel As Integer)

             If MsgBox("There has been done some changes. You wish to save these changes ?", vbQuestion + vbYesNoCancel, "Save changes") = vbYes Then

              'do nothing and Access saves automatically

             ElseIf vbNo Then
              DoCmd.RunCommand acCmdUndo

             ElseIf vbCancel Then
              SomeVariable = 1
             End If

     End Sub

Private Sub Form_Unload(Cancel As Integer)

If SomeVariable = 1 Then
 SomeVariable=0
 Cancel = True
End If

End Sub

Any way to fix this ?

Upvotes: 0

Views: 1041

Answers (1)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

You must save the return value from MsgBox, then proceeed accordingly:

        Dim vbAnswer
        vbAnswer= MsgBox("There has been done some changes. You wish to save these changes ?", vbQuestion + vbYesNoCancel, "Save changes")

        if vbAnswer = vbYes Then

          'do nothing and Access saves automatically

         ElseIf vbAnswer= vbNo Then
               ....
         ElseIf vbAnswer= vbCancel Then

Upvotes: 1

Related Questions