Executing Function procedures
Functions, unlike Sub procedures, can be executed in only two ways:
✓ By calling the function from another Sub procedure or Function procedure ✓ By using the function in a worksheet formula
Try this simple function. Enter it into a VBA module:
Function CubeRoot(number)
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, however, 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.
No comments:
Post a Comment