user1762087
user1762087

Reputation: 460

visual basic for application - error handling

I have never worked with VBA, therefore this could by an easy task, but I can't get it working :-) Simply I need to catch a run time error in following code :

Private Sub CheckBox1_Click()

ActiveWorkbook.Sheets("(X)").Unprotect
ActiveWorkbook.Sheets("(X)").Select
ActiveSheet.Range("F18").Select
'here comes the error
ActiveSheet.Range("$A$2:$X$310").AutoFilter Field:=1, Criteria1:="1"
Sheets("(40 UKÁŽKA)").Protect DrawingObjects:=True, Contents:=True, Scenarios:=True
End Sub

Upvotes: 2

Views: 354

Answers (2)

chuff
chuff

Reputation: 5866

Use On Error. See this for a good discussion of the topic.

      On Error GoTo ErrHandler

      <do things>

      On Error GoTo  0 'Turn default error handling back on

      Exit Sub

 ErrHandler:

     If Error.Number = xxxx Then

         <error processing>

     End If

     (then Resume )(or  Resume Next) (or do nothing & let sub end)

 End Sub     

Upvotes: 2

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

Welcome to old school error handling.

What you are looking for is either

Sub MySub()
  On Error Resume Next
    DoMyStuff()
End Sub

if you want to swallow this issue, e.g equivalent of Try Catch End

or

Sub MySub()
  On Error Goto ErrorHandler
    DoMyStuff()
  KeepGoing :
    DoSomeMoreStuffAnyway() 
  Exit Sub

ErrorHandler:
  HandleTheError()
Exit Sub

You can get the Error number from the variable Err You can also fix and call Resume to go to the next line of code after the error happened You can also do Resume To a lable e.g. Resume KeepGoing in the above.

More info here MSDN VBA Error Handling

Upvotes: 2

Related Questions