Executing Sub procedure
Although you may not know much about developing Sub procedures at this point, I’m going to jump ahead a bit and discuss how to execute these procedures. This is important because a Sub procedure is worthless unless you know how to execute it.Executing a Sub procedure means the same thing as running or calling a Sub procedure. You can use whatever terminology you like.
You can execute a VBA Sub in many ways — that’s one reason you can do so many useful things with Sub procedures. Here’s a list of the ways to execute a Sub procedure:
- With the Run ⇨ Run Sub/UserForm command (in the VBE). VBE executes the Sub procedure in which the cursor is located. This menu command has two alternatives: the F5 key and the Run Sub/UserForm button on the Standard toolbar in the VBE. These methods don’t work if the procedure requires one or more arguments.
- From another Sub procedure that you write.
- From a custom item on the ribbon you develop.
- From the Immediate window in the VBE. Just type the name of the Sub procedure and press Enter.
- From Run Macro ⇨ Select Macro you want to run. By this, your macro runs the Sub procedure without opening VBE.
- Open the VBE in your CAD software.
- Enter the following code into your module
Example
Sub CubeRoot()
Number = InputBox(“Enter a positive number.”)
MsgBox number ^ (1/3) & “is the cube root.”
End Sub
I entered 4 as input value. And get result as shown in below image.
By the way, CubeRoot is not an example of a good macro. It doesn’t check for errors, so it fails easily. To see what I mean, try clicking the Cancel button in the input box or entering a negative number.
Executing the Sub procedure directly
The quickest way to execute this procedure is by doing so directly from the VBA module in which you defined it. Follow these steps:- Activate the VBE and select the VBA module that contains the procedure.
- Move the cursor anywhere in the procedure’s code.
- Press F5 (or choose Run ⇨ Run Sub/UserForm).
- Respond to the input box and click OK.
You can’t use the Run ⇨ Run Sub/UserForm command to execute a Sub procedure that uses arguments, because you have no way to pass the arguments to the procedure. If the procedure contains one or more arguments, the only way to execute it is to call it from another procedure — which must supply the argument(s).
Executing the Sub procedure from another procedure
You can also execute a Sub procedure from another procedure. Follow these steps if you want to give this a try:- Activate the VBA module that holds the CubeRoot routine.
- Enter this new procedure (either above or below CubeRoot code — it makes no difference):
- Execute the NewSub macro.
Example
Sub NewSub()
Call CubeRoot
End Sub
No comments:
Post a Comment