How to stop VBA macro automatically?

前端 未结 3 1046
-上瘾入骨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:29

    I believe want you want to do is raise the error again in your error handling code. Try something like this (not tested):

    Private Sub Test
        On Error Goto bad
        x = 0
        debug.print 1/x
        Exit Sub
    
        bad:
            'Clean up code
            Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext
    End Sub
    

    When using On Error Goto, you need an Exit Sub before the label. Otherwise your code will fall through to the error handler even when there is no error.

    Your first error handling doesn't catch actual errors that might occur during runtime other than what you are testing for. Also, there is not a convenient way to signal the calling function that something went wrong unless you add checks in all the calling routines.

    Note that it's generally considered bad design though to raise an error only for flow control:

    Private Sub Test
        If x = 0 Then
            Err.Raise 
        End If
    End Sub
    

提交回复
热议问题