VBA: How long does On Error Resume Next work?

前端 未结 4 1121
日久生厌
日久生厌 2020-11-28 15:55

I\'m reading up on how to use On Error Resume Next and I\'m trying to figure out how long that line will apply to the program. On the Microsoft site, I found t

相关标签:
4条回答
  • 2020-11-28 16:26

    To answer your question "How long does On Error Resume Next work?"

    The answer is: until the next definition of On error ...

    So if you define an On error resume next, it will skip every error until you define a On error goto 0 or On error goto label

    0 讨论(0)
  • 2020-11-28 16:27

    SCOPE OF ON ERROR... STATEMENT

    The effec5 of ON ERROR ... ends as soon as one of the following is encountered:

    1. Another ON ERROR .... (Maybe in the form of ON ERROR RESUME x or ON ERROR GOTO x)
    2. Exit Sub / Exit Function within the same sub/function where defined.
    3. End Sub / End Function of the sub/function where defined.

    IS IT BAD TO USE ON ERROR RESUME NEXT?

    Yes and No.

    I would say don't use without knowing what the effect of this statement would be. Avoid if possible. Keep the scope short wherever not possible.

    To nullify the effect of an ON ERROR RESUME NEXT statement, you can call ON ERROR GOTO 0

    0 讨论(0)
  • 2020-11-28 16:44

    You don't always need a bunch of code to handle an error, but you really should do something with it. Maybe just have your code change the cells.font.color property to vbRed. Simply doing On Error Resume Next (a line of code that might error) On Error Goto 0 is terribly poor form.

    And like others have pointed out, On Error Goto Label is essentially VBA's version of Try ... Catch, and I use it frequently

    0 讨论(0)
  • 2020-11-28 16:48

    You only want to use "On Error Resume Next" when

    1. You know why the error occurs.

    2. You know that it will not affect other parts of the code.

    3. You use "On Error Goto 0" immediately after the code where the error occurs.

    Having said that, you should almost NEVER use it. You should figure out why the error occurs and code to handle it.

    What the website is saying is that once your are out of the sub or function that called it the resume next will no longer be in affect and your errors will raise as they should.

    A better alternative is to use goto in this fashion. But some people frown on this almost as much.

    sub SomeSub()
        On Error Goto TestFailed
    
        'Some code
    
        'Some code
    
        'Some code
    
    Exit sub
    
    TestFailed:
        'Some code here to alert you to and/or handle the fallout of the error.
    End sub
    
    0 讨论(0)
提交回复
热议问题