Sunday, December 5, 2010

Error Handling - Find Method

How to handle an error when the value which you are searching is not available in Excel sheet.

Sub Err_Hnd()

Dim M_Rng as Range
Sheets("My Sheet").Select
On Error Resume Next
Set M_Rng = Sheets("My Sheet").Columns(1).Find(What:=Test_PID, after:=Cells(1, 1), LookIn:=xlValues,
                    LookAt:=xlPart, SearchOrder:=xlByRows, _
                    searchdirection:=xlNext, MatchCase:=False)
On Error GoTo 0

If M_Rng Is Nothing Then GoTo Err_H:
'''' if M_Rng has returned any value then your code execution starts from here
Err_H:
           '''' based on the error what has to be done
           ''' exit sub
End Sub

Below are the Error Handler Options in Excel VBA-
  • On Error GoTo
    Enables the error-handling routine that starts at , which is any line label or line number. The specified line must be in the same procedure as the On Error statement.
  • On Error Resume Next
    Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred. In other words, execution continues.
  • On Error GoTo 0
    Disables any enabled error handler in the current procedure.
In the above example what we are doing is allowing the execution of the macro to proceed if an error occurs (i.e, using the On Error Resume Next )
Subsequently we are disabled the error handler using On Error GoTo  0
Now we are checking the Range variable if it contains Nothing, if yes then we take the code execution to the error handler label, otherwise the execution proceeds as usual.

No comments:

Post a Comment