VBA: Hands-On Introduction to VBA Programming
7
Several principles are demonstrated in this example.
• Functions are used to return values (and Objects).
• Parameters for Functions and Procedures are placed between the parenthesis that follow the Name of the Function or
Procedure.
• Return values for Functions are set by assigning a value to the name of the Function. In this example, the Function is
named “CalculateAreaRectangle” so we use “CalculateAreaRectangle = Width * Height”.
• Code execution can jump from one Procedure or Function to another but returns to the calling Procedure or Function
after execution is complete.
Let’s take a look at the Code Module “FP2”.
“FP2” contains one Procedure and two Functions. Follow
the code execution by looking at the screen capture shown
here. Begin with “TestAreaCircle” and number the lines as
they will be executed. Keep in mind that Variable
Declarations are not executable.
Take a look at the Function “Pi”. This function returns a
value for Pi so we do not need to hard-code the value, we
can just use the Pi function.
What do we have here? Running the Procedure
“TestAreaCircleB” provides the same results as running
“TestAreaCircle”. It does so without the use of any other
Functions or Procedures. So, why would we divide up our
code when we can have it all in one Procedure?
Any time a section of code can be broken out into it’s own Function or Procedure, it should be looked at very carefully. Consider
the Pi function. Today, it’s value is 3.14. What if we decide 2 months from now that we need a more accurate number? If we
do not use a function, we may find that number in 100 different places. We would need to replace 3.14 with 3.14159 in 100
different places. If we had used a Function (as we are in FP2), we would only have to make a change in one place. And if
tomorrow we decide we need more accuracy than 3.14159, we could use the line of code:
Pi = Atn(1) * 4
Let’s make that change right now. In the Pi Function, change the code from “Pi = 3.14” to “Pi = Atn(1) * 4”. This calculation will
return a very precise value for Pi.
Parameters in Functions and Procedures
Some Functions and Procedures make use of Parameters. These are variables that get passed into the Function or Procedure
that make the Function or Procedure dynamic – the results are based on the Parameter. For example, the
“CalculateAreaRectangle” Function. This Function has two parameters, the Width and Height.
Open the Code Module “FP3” in the active project. We will begin by typing in two Functions. DTR (Degrees to Radians) and
RTD (Radians to Degrees).