Ls the macro perfect yet

Now this code is absolutely perfect, right? Not quite. Try running the procedure while the active sheet is a Chart sheet. As shown in Figure 12-3, Excel displays another message that's as illuminating as the other error messages you've seen. This error occurs because there is no active cell on a Chart sheet.

Figure 12-3:

Running the procedure when a chart is selected generates this error.

Figure 12-3:

Running the procedure when a chart is selected generates this error.

The following listing uses the TypeName function to make sure the selection is a range. If anything other than a range is selected, this procedure displays a message and then exits:

Sub EnterSquareRoot4() Dim Num As Variant ' Make sure a worksheet is active

If TypeName(Selection) <> "Range" Then MsgBox "Select a range first." Exit Sub End If

' 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