JT2013
JT2013

Reputation: 643

Modify VBA code for saving - MS Access

I am not much of a VBA programmer but I have been using the following code to prompt a user before exiting a form whether to save the changes or not. The code is the following:

Private Sub Form_BeforeUpdate(Cancel As Integer)


   Dim ctl As Control

   On Error GoTo Err_BeforeUpdate


   If Me.Dirty Then

      If MsgBox("Do you want to save?", vbYesNo + vbQuestion, _
              "Save Record") = vbNo Then
         Me.Undo
      End If
   End If

Exit_BeforeUpdate:
   Exit Sub

Err_BeforeUpdate:
   MsgBox Err.Number & " " & Err.Description
   Resume Exit_BeforeUpdate
End Sub  

Anytime that i try to print the report to PDF, it always prompts the user whether or not to save. I would like the above code to be written in such a way that it always prompts the user whether or not to save the record except for when someone wants to print.

Can someone help modify this code?

Thanks in advance!

Upvotes: 1

Views: 2011

Answers (1)

HansUp
HansUp

Reputation: 97131

When you attempt to print a bound form which is "dirty" --- meaning it includes unsaved changes --- Access automatically performs a save before printing.

The problem you're facing is that your form includes a Form_BeforeUpdate procedure which asks the user whether to store or discard unsaved changes, and Access processes that Form_BeforeUpdate procedure immediately before each save operation.

Your VBA code to print the form could first perform the save itself, then print ...

If Me.Dirty = True Then
    Me.Dirty = False ' saves changes to current record
End If
' insert your print statement here

A possible problem with that approach is it would force a save without user confirmation every time you want to print ... which may not be acceptable.

If your goal is to also permit the users to print a form which contains unsaved data, you may be out of luck ... assuming it's a bound form.

Upvotes: 2

Related Questions