VBA: How long does On Error Resume Next work?

前端 未结 4 1131
日久生厌
日久生厌 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: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
    

提交回复
热议问题