Using Custom Procedures
You can create procedures and save those procedures in a standard module. Those procedures can be either subprocedures or functions. Subprocedures and functions are quite similarthe essential difference is that subprocedures don't return a value, whereas functions do return a value.
A custom procedure differs from an event procedure in two principal ways:
-
A custom procedure can be saved in a standard module or a form's class module. The procedure must be saved in a standard module if it's called from procedures in several forms' class modules. The procedure can be saved in a form's class module if it's called only from procedures within that class module. An event procedure is always saved in a class (behind a form) module.
-
A custom procedure doesn't directly respond to an event, as does an event procedure. A custom procedure is called from an event procedure or from another custom procedure.
The main reason for using custom procedures is to avoid unnecessary duplication of code and to save you a lot of work. Here's an example to show you what I mean.
Suppose that you have several command buttons on a form and you need to write event procedures for all of them. Each of these event procedures contains some code that determines what makes each command button different. Quite likely, each event procedure contains some code that's the same for several buttons. Instead of repeating that code in all the event procedures, you can write that code in a separate subprocedure and call that subprocedure from each event procedure. Simply include the name of the subprocedure within the event procedure to call the subprocedure.
In outline form, here's an example of a subprocedure that can be called from an event procedure:
Public Sub EnableButtons() Place the shared statements here End Sub
Also, in outline form, here's an example of an event procedure that calls the subprocedure:
Private Sub cmdSave_Click() Some statements EnableButtons Some more statements End Sub
Notice that the subprocedure in this example is named EnableButtons and is declared as a public procedure so that it's available in modules other than the standard module in which it is saved.
The event procedure contains a statement that consists of the name of the subprocedure. When this statement executes, the subprocedure runs.
NOTE
Another benefit of creating custom procedures for code that's used in several places is that it simplifies program maintenance. If it becomes necessary to modify the code, you have to do so only in one place instead of separately in every place that code is repeated.