How to stop VBA macro automatically?

前端 未结 3 1014
-上瘾入骨i
-上瘾入骨i 2021-01-05 16:03

I know you can manually stop a running VBA macro with Ctrl+Break, but is there any way to have the code stop automatically if a certain condition is me

3条回答
  •  悲哀的现实
    2021-01-05 16:27

    You can raise your own user-defined error with err.raise. This is similar to your example, but a little more powerful in that it is an actual error that will halt code execution, even if it's applied to a nested call.

    For example,

    sub a
    on error goto exitCode
        call b
        msgbox "a complete"
        exit sub       'you need this to prevent the error handling code from always running
    exitCode:
        msgbox "code is exiting..."
        'clean up code here
    end sub
    
    sub b
        call c
        msgbox "b complete"
    end sub
    
    sub c
        msgbox "entering c"
        err.raise 555, "foo", "an error occurred"
        msgbox "exiting c"
    end sub
    
    'OUTPUT:
    
    'entering c
    'code is exiting...
    

    The err.raise line will send the control to the exitCode: label even though it was called outside of a. You could use any conditions to test if this custom error should be thrown.

    More on the err object and VBA error handling-

    https://msdn.microsoft.com/en-us/library/ka13cy19(v=vs.90).aspx

    http://www.cpearson.com/excel/errorhandling.htm

提交回复
热议问题