How Do I Use Code Posted?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Crobar
    New Member
    • Jan 2015
    • 2

    How Do I Use Code Posted?

    Hello TheSmileyCoder. <Fingers crossed that this thread isn't tool old :) > I am trying to implement your recommended solution for this problem, but I do not know where to paste the code. I'm using Access 2013. How do I perform this?

    Thank you!

    <Mod Edit NeoPa>
    This has been moved into a new question thread as hijacking threads is not allowed.
    The thread it came from is How do I Save Data on Form Only After Button Clicked.
    Last edited by NeoPa; Jan 4 '15, 03:41 AM. Reason: Moved to new thread.
  • twinnyfo
    Recognized Expert Moderator Specialist
    • Nov 2011
    • 3662

    #2
    Crobar,

    Insert the declaration at the top of your form, before any Subs or Functions.

    The next block of code is added to the OnClick event of your Save Button (you must have a Save Button to use the code).

    The third block of code is added to the Form's BeforeUpdate Event. Your code on the form should look something like this:

    Code:
    Option Compare Database
    Option Explicit
    
    Private bSaveClicked as Boolean
    
    Private Sub Form_BeforeUpdate(Cancel As Integer)
        If Not bSaveClicked Then
            MsgBox "You are trying to navigate away from the " & _
                "active record. Please either save your " & _
                "changes, or press ESC to cancel your changes.", _
                VbOkOnly + vbInformation
            Cancel=True
        End If
    End Sub
    Private Sub cmdSave_Click()
        bSaveClicked=True
        On Error Resume Next
        Docmd.Runcommand acCmdSaveRecord
        bSaveClicked=False
    End Sub
    Thanks to Smiley for the code (I did change the name of the Class variable to match the rest of the code). NB: I did not include any error handling, which I always recommend for every sub and function.

    Hope this hepps!

    Comment

    • Crobar
      New Member
      • Jan 2015
      • 2

      #3
      Hi twinnyfo,

      Thank you for the reply. The part I am confused about is what is meant by "top of the form"?. If I'm looking at the form in design view, where would this code go?

      I'm an Access newb, learning from Google as I go.

      Thanks again!

      Comment

      • twinnyfo
        Recognized Expert Moderator Specialist
        • Nov 2011
        • 3662

        #4
        I mis-spoke. It should be at the top of the VBA module behind your form. Clicking the "Code" button when the form is in design view will open the VBA module for that Form.

        I hope this helps!

        Comment

        Working...