Calling the function from a Sub procedure

Because you can't execute this function directly, you must call it from another procedure. Enter the following simple procedure in the same VBA module that contains the CubeRoot function:

Sub CallerSub()

Ans = CubeRoot(125) MsgBox Ans End Sub

When you execute the CallerSub procedure (using any of the methods describes earlier in this chapter), Excel displays a message box that contains the value of the Ans variable, which is 5.

Here's what's going on: The CubeRoot function is executed using an argument of 125. The function returns a value. That value is assigned to the Ans variable. The MsgBox function then displays the value in the Ans variable. Try changing the argument that's passed to the CubeRoot function and run the CallerSub macro again. It works just like it should.

By the way, the CallerSub procedure could be simplified a bit. The Ans variable is not really required. You could use this single statement to obtain the same result:

0 0

Post a comment