Knowing when to ignore errors

In some cases, it's perfectly okay to ignore errors. That's when the On Error Resume Next statement comes into play.

The following example loops through each cell in the selected range and converts the value to its square root. This procedure generates an error message if any cell in the selection contains a nonpositive number:

Sub

SelectionSqrt()

Dim cell As Range

If TypeName(Selection) <> "Range" Then Exit Sub

For Each cell In Selection

cell.Value = Sqr(cell.Value)

Next cell

End

Sub

In this case, you may want to simply skip any cell that contains a value you can't convert to a square root. You could create all sorts of error-checking capabilities by using If-Then structures, but you can devise a better (and simpler) solution by simply ignoring the errors that occur.

The following routine accomplishes this by using the On Error Resume Next statement:

Sub

SelectionSqrt()

Dim cell As Range

If TypeName(Selection) <> "Range" Then Exit Sub

On Error Resume Next

For Each cell In Selection

cell.Value = Sqr(cell.Value)

Next cell

End

Sub

In general, you can use an On Error Resume Next statement if you consider the errors inconsequential to your task.

0 0

Responses

Post a comment