Search code examples
excelvbaerror-handlingexit-code

Can someone help me modify my script? To exit sub on error after line 7?


Sub shutdownbot()



Application.ScreenUpdating = False
Application.Calculation = Application.Calculation =xlCalculationManual
Application.DisplayAlerts = False
Application.EnableEvents = False
Windows("FlaggingreportBOTv2.xlsb").Activate  
Windows("Post 7am routing risk level v5.2.xlsb").Activate. 

‘when the end user opens the file I expect this line to error then exit the sun with any error messages on screen being supressed

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
Application.EnableEvents = False

End sub 

Solution

  • You can use On error resume next.

    As you should use this very carefully it is recommended to always comment, why you think it is ok to use On error resume next in this case. And reset the error handling as soon as possible by inserting On error goto 0 or On error goto xxx

    
    Sub shutdownbot()
    
    Application.ScreenUpdating = False
    Application.Calculation = Application.Calculation =xlCalculationManual
    Application.DisplayAlerts = False
    Application.EnableEvents = False
    Windows("FlaggingreportBOTv2.xlsb").Activate  
    
    ‘when the end user opens the file I expect this line to error then exit the sun with any error messages on screen being supressed
    
    On error resume next
    Windows("Post 7am routing risk level v5.2.xlsb").Activate. 
    On error goto 0
    
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.DisplayAlerts = False
    Application.EnableEvents = False
    
    End sub