Difference between 'on error goto 0' and 'on error goto -1' — VBA

前端 未结 3 1766
有刺的猬
有刺的猬 2020-11-27 12:55

Can anyone find the difference between \'On error goto -1\' and \'on error goto 0\' in VBA? I\'ve tried google and msdn, but I\'ve had no luck.

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 13:33

    This answer addresses the confusion between the error object and the error handler.

    The error object can be cleared using Err.Clear. This does not affect the error handler.

    The error handler becomes enabled by using On Error Goto . It becomes active when an error occurs.

    While the error handler is active, you can not assign a new error handler. On Error Goto will have no effect. VBA simply ignores the attempt to assign a new error handler.

    Using Err.Clear does not cancel the error handler.

    Jumping to a different place in the code using Goto does not cancel the error handler. Using Goto in an error handling block can cause confusion and should be avoided. You might think the error handler is no longer active when in fact it is still active.

    The effect of an active error handler is that you can not assign a new error handler. On Error Goto will have no effect. VBA simply ignores the attempt to assign a new error handler. Any additional errors will be unhandled while the error handler is active.

    The only way to exit an active error handler is:

    1. Resume
    2. Resume Next
    3. Resume
    4. On error goto -1
    5. exit the procedure

    Using any one of these ways to exit the error handler will also clear the error object.

    Excellent source: Pearson Error Handling In VBA Chip Pearson doesn't mention On error goto -1 in his article. To quote him:

    I deliberately did not include On Error GoTo -1 because it serves no real purpose and can lock up the entire Excel application unless used in exactly the right way. Yes, On Error GoTo -1 is syntactically valid, but it is like giving a gun to drunk teenager. Nothing good will come from it.

    You can also handle errors inline without using an error handler using the error object: MSDN Inline Error Handling

提交回复
热议问题