An Erroneous Example. Microsoft Excel VBA Programming
Reklamë
Reklamë
184
Part III: Programming Concepts
The ultimate goal of error handling is to write code that avoids displaying
Excel’s error messages as much as possible. In other words, you want to anticipate potential errors and deal with them before Excel has a chance to rear its ugly head with a (usually) less-than-informative error message.
An Erroneous Example
To get things started, I developed a short VBA macro. Activate the VBE, insert a module, and enter the following code:
Sub EnterSquareRoot()
Dim Num As Double
‘ Prompt for a value
Num = InputBox(“Enter a value”)
‘ Insert the square root
ActiveCell.Value = Sqr(Num)
End Sub
As shown in Figure 12-1, this procedure asks the user for a value. It then performs a magical calculation and enters the square root of that value into the active cell.
Figure 12-1:
The
InputBox function displays a dialog box that asks the user for a value.
You can execute this procedure directly from the VBE by pressing F5.
Alternatively, you may want to add a button to a worksheet (use Developer➪
Controls➪Insert and select the Form controls button to do this) and then assign the macro to the button. (Excel prompts you for the macro to assign.)
Then you can run the procedure by simply clicking the button.
Shkarko
Reklamë