Subs vs. Functions


Think, for a moment, about what a sub does. It can

  • Accept parameters from the procedure that is calling it;

  • Take those arguments and carry out a series of instructions.

Like a sub, a function does these two things as well. Unlike a sub, though, a function returns a value to the caller. The data type of that value is defined by the As type clause of the function declaration. To use the example of the fullName function that we developed in Chapter 9, its declaration was:

Function fullName(strFname As String, strLname As String) As String

The fullName function, then, returns a String value. In the body of the function, the actual value returned by the function is determined by the value assigned to a variable whose name is the same as the function.

If you’d like to review functions and the way in which they differ from subs, see the “Functions” section in Chapter 9.

Typically, you call a function precisely because of the value that it returns. But interestingly, you can call a function as if it were a sub and ignore its return value. For example, you could call the fullName function from Chapter 9 and discard its return value by using the following code:

Sub callFullName()   fullName "John", "Public" End Sub 

In this function call, the parentheses surrounding the function arguments have been removed, and the function’s return value has not been assigned to a variable or referenced in any other way. We have treated our function and called it as if it were a sub.

In most cases, of course, you wouldn’t want to discard a function’s return value, since that would make it completely pointless to call the function in the first place. But there are some cases in which you are interested in an operation that the function performs, but you don’t care about the value that a function returns. This is particularly true when it returns a Boolean indicating success or failure, and you either don’t care about the result of the function call or you’re certain it will succeed.

The functions that you code yourself (they’re often called user-defined functions) are not the only functions that you’ll be using. They may not even be the primary functions that you use. Visual Basic comes with an extensive set of function libraries. These functions, which are called intrinsic functions because they are built into VBA, provide such services as string handling, file input and output, mathematical and numerical operations, date and time manipulation, and handling input and output. Although you’ve already used some of these intrinsic functions, in the next section we’ll look at them in greater detail.




Access VBA Programming
Microsoft Access VBA Programming for the Absolute Beginner
ISBN: 1598633937
EAN: 2147483647
Year: 2006
Pages: 214
Authors: Michael Vine

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net