The macro is still not perfect

So the modified EnterSquareRoot procedure is perfect, right? Not really. Try entering text instead of a value. Or click the Cancel button in the input box. Both of these actions generate an error (Type mismatch).

The following modified code uses the IsNumeric function to make sure that Num contains a numeric value. If the user doesn't enter a number, the procedure displays a message and then stops. Also, notice that the Num variable is now defined as a Variant. If it were defined as a Double, the code would generate an unhandled error if the user entered a nonnumeric value into the input box.

Sub

EnterSquareRoot3()

Dim Num As Variant

'

Prompt for a value

Num = InputBox("Enter a value")

'

Make sure Num is a number

If Not IsNumeric(Num) Then

MsgBox "You must enter a number."

Exit Sub

End If

'

Make sure the number is nonnegative

If Num < 0 Then

MsgBox "You must enter a positive number."

Exit Sub

End If

'

Insert the square root

ActiveCell.Value = Sqr(Num)

End

Sub

0 0

Post a comment