30.04.2017 Views

4523756273

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5: VBA Sub and Function Procedures<br />

73<br />

4. Choose Insert➪Module to insert a new module.<br />

5. Enter the following into the module:<br />

Sub CubeRoot()<br />

Num = InputBox(“Enter a positive number”)<br />

MsgBox Num ^ (1/3) & “ is the cube root.”<br />

End Sub<br />

This procedure asks the user for a number and then displays that number’s<br />

cube root in a message box. Figures 5-1 and 5-2 show what happens when you<br />

execute this procedure.<br />

Figure 5-1:<br />

Using the<br />

built-in VBA<br />

InputBox<br />

function to<br />

get a<br />

number.<br />

Figure 5-2:<br />

Displaying<br />

the cube<br />

root of a<br />

number via<br />

the MsgBox<br />

function.<br />

By the way, CubeRoot is not an example of a good macro. It doesn’t check for<br />

errors, so it fails easily. To see what I mean, try clicking the Cancel button in<br />

the input box or entering a negative number.<br />

Executing the Sub procedure directly<br />

The quickest way to execute this procedure is by doing so directly from the<br />

VBA module in which you defined it. Follow these steps:<br />

1. Activate the VBE and select the VBA module that contains the<br />

procedure.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!