Share this Page URL

Functions and Subprocedures > Functions and Subprocedures - Pg. 419

Some parameters are passed with the intent that their values won't be changed (i.e., they're read-only inside a function). This is called passing by value, and such pa- rameters are preceded by the ByVal keyword. You may also pass parameters to receive values back from the function or subprocedure call. These parameters are preceded by the ByRef keyword and are passed by reference. Functions and subprocedures are denoted by the Function and Sub keywords, re- spectively. To begin the body of a function or subprocedure, use one of these key- words in conjunction with the routine's name and parameter list. End the routine with the End keyword followed by Function or Sub . For example, suppose you have a subprocedure that displays a message. Pass it the message as a string and the pro- cedure formats it and displays it in a message box (Example 18-17). Example 18-17. Passing a Subroutine's Message as a String Public Sub DisplayMsg(ByVal strMsg As String) MsgBox "Important message: " & strMsg End Sub Notice that the subprocedure begins with the Public keyword. This determines the scope of the procedure (more on this in Section 18.4.7). The routine's name is DisplayMsg , and it is being passed a string in the variable called strMsg . Since strMsg is passed by value, we cannot modify its value in our subprocedure's body. Like all subprocedures, ours ends with End Sub . To call a subprocedure, type its name followed by its parameters (separated by commas if there is more than one), as shown in Example 18-18. Example 18-18. Calling a Subprocedure DisplayMsg "This is a string to display." As I mentioned earlier, a function returns a value (called, strangely enough, the return value ) to the part of the program that calls it. Declare the data type of a function's return value after the function's parameter list, and assign its value to the function's name. Take a look at a function that calculates a circle's area in Example 18-19. Example 18-19. Building a Function Const PI = 3.14 Public Function CalcCircleArea(ByVal dblRadius As Double) _ As Double CalcCircleArea = PI * (dblRadius^2) End Function The function CalcCircleArea takes a decimal number (denoted by Double) as a circle radius, squares it and multiplies it by the pi constant, and returns the result (by Working with VBA A VBA Language Primer | 419