Calling Procedures and Returning from Them

The previous section discusses calling procedures. You have learned about the Call keyword, but you haven’t been exposed to Call before now. That is, you haven't been directly exposed to Call even though you have performed a similar action by using the built-in Val() and Format() functions.

When one procedure contains a Call statement, the Call statement puts the current procedure on hold and executes the called procedure. Here is one of the formats of the Call statement:

Call Procedure

note

The Call keyword is sometimes optional, as you’ll see later in this lesson. The Call keyword is very rarely used in VB programs.

When one procedure’s execution reaches its Call statement, that procedure is put on hold and execution begins at the called Procedure. After the called procedure ends (whether it ends with the End Sub statement or an Exit Sub statement or by other means), the called procedure returns control to the calling procedure. The same thing happens when you call the built-in functions because a built-in function is a special kind of procedure: Your code temporarily stops, and the built-in function’s code takes over and uses the argument(s), and finally returns a value as well as control back to your code.

You’ve seen event procedures and you’ve executed the built-in function procedures, and Visual Basic supports two other kinds of procedures:

  • Standard subroutine procedures
  • Standard function procedures that you write

A standard subroutine or function procedure doesn't respond to an event. A standard procedure only executes when called from elsewhere in the program.

caution

If a procedure is defined with the Private keyword, only procedures elsewhere within that module can call that procedure. If a procedure is defined with the Public keyword, all procedures in the project can call the procedure.

Standard procedures, whether they are subroutines or functions, can reside either inside a form module (following the event procedures) or inside an external module file you add to your project. The calling code calls both and they both do work. The subroutine doesn't return a value to the calling procedure. The function does return a value to the calling procedure, and the calling procedure must do something with that value such as assign the value to a variable or control.

When you want to write a procedure that performs a task but doesn't need to return a value, write a subroutine procedure. If you need to write a procedure that performs a task and returns a value, such as a calculated result, write a function procedure. You can pass arguments to either kind of procedure.

note

A standard function procedure is a standalone nonevent procedure that does work when called by another procedure and returns a single value to that called procedure. A standard subroutine procedure is a standalone nonevent procedure that does work when called by another procedure.

Top Home