0

I have a series of forms and on each one I would like to add a Back button, so I created a command button and to the on click event assigned it trigger the following VBA;

Private Sub cmdBack_Click()
On Error GoTo Err_CmdBack_Click

    If Me.Dirty Then Me.Dirty = False
    DoCmd.Close

Exit_CmdBack_Click:
    Exit Sub

Err_CmdBack_Click:
    MsgBox Err.Description
    Resume Exit_CmdBack_Click

End Sub

How can I now, or what is the best way, to copy this button to all the other forms with the code? If I just copy and paste I lose the code and I don't want to re-write the code for each button that seems inefficient.

Naz
  • 900
  • 2
  • 10
  • 25
  • But that's what you have to do: _copy button, copy code._ – Gustav Nov 28 '17 at 09:47
  • @Gustav But what about an embedded macro? I've used that before but I don't know how to change the VBA to one of those. Then it's wrote once assign many? – Naz Nov 28 '17 at 09:51
  • You wouldn't want that. Using those, turns debugging into a potential nightmare. – Gustav Nov 28 '17 at 10:18

1 Answers1

2

There are many ways to go about code reusability in forms in Access.

For this example, you could simply use a function in a separate module, and bind the button to that:

Public Function formBack()
On Error GoTo Err_CmdBack_Click

    If Screen.ActiveForm.Dirty Then Screen.ActiveForm.Dirty = False
    DoCmd.Close

Exit_CmdBack_Click:
    Exit Function

Err_CmdBack_Click:
    MsgBox Err.Description
    Resume Exit_CmdBack_Click
End Function

(If you press a button on a form, it's always the active form).

You can bind the button to this function by setting it's On Click property to =formBack()

There are alternate ways to reuse code. This question has some nice answers, demonstrating some of the more complex ones.

Naz
  • 900
  • 2
  • 10
  • 25
Erik A
  • 31,639
  • 12
  • 42
  • 67