Executing Function procedure
Function procedures, unlike Sub procedures, can be only executed in only one way:
- By calling the function from another Sub procedure or Function procedure.
Try this simple function. Enter it into a VBA module:
Example
Function CubeRoot()
CubeRoot = number ^ (1/3)
End Function
This function is pretty wimpy — it merely calculates the cube root of the number passed to it as its argument. It does, provide a starting point for understanding functions. It also illustrates an important concept about functions: how to return the value. (You do remember that a function returns a value, right?)
Notice that the single line of code that makes up this Function procedure performs a calculation. The result of the math (number to the power of 1⁄3) is assigned to the variable CubeRoot. Not coincidentally, CubeRoot is also the name of the function. To tell the function what value to return, you assign that value to the name of the function.
Executing the Function procedure from a Sub procedure
Because you can’t execute a function directly, you must call it from another procedure. Enter the following simple procedure in the same VBA module that contains the CubeRoot function:
Example
Sub CubeRoot()
Ans = CubeRoot(125)
MsgBox Ans
End Sub
When you execute the CubeRoot procedure (using any of the methods described earlier), Your CAD software displays a message box that contains the value of the Ans variable, which is 5.
Here’s what’s going on:
- CubeRoot(125) means it CubeRoot receive argument of 125.
- Then Function CubeRoot(number) is executed. As described previously, number is an argument. And here the value of this is 125.
- Then by “number ^ (1/3)” we get the cube of 125. (why? Because 125 is argument passed by the sub function and this 125 is the value of "number".)
- After that cube value of 125, i.e. 5, is assigned to or given to or equal to CubeRoot. This CubeRoot assigned to or given to or equal to Ans. After that message boxes show the value of 5 in your screen.
No comments:
Post a Comment