Revisiting the Enter SquareRoot procedure

Examine the following code. I modified the routine from the previous section by adding an On Error statement to trap all errors and then checking to see whether the InputBox was cancelled.

Sub EnterSquareRoot5() Dim Num As Variant Dim Msg As String

' Set up error handling On Error GoTo BadEntry

' Prompt for a value

Num = InputBox("Enter a value")

' Exit if cancelled

' Insert the square root

ActiveCell.Value = Sqr(Num) Exit Sub

BadEntry:

Msg = "An error occurred." & vbNewLine Msg = Msg & "Make sure a range is selected " Msg = Msg & "and you enter a nonnegative value." MsgBox Msg End Sub

This routine traps any type of run-time error. After trapping a run-time error, the revised EnterSquareRoot procedure displays the message box shown in Figure 12-4.

Figure 12-4:

A run-time error in the procedure generates this helpful error message.

Figure 12-4:

A run-time error in the procedure generates this helpful error message.

0 0

Post a comment