Marius Katinas
Marius Katinas

Reputation: 470

How to stop Excel Macro Which Still Runs After Application.Quit Method

I have found similar questions, but for other issues, seems that Excel is called from another application and process is left after Excel application closes.

In my case, I have a macro in my Excel file, and I try to close the application when an error occurs.

I have my error handling set this way:

'Code code code

        CleanExit:
        Logger.LogData LOG_DEBUG, MODULE_NAME, "Initialize", "Some module initialized!"
        Exit Function

    ErrorExit:
        Logger.LogData LOG_ERROR, MODULE_NAME, "Initialize", "Error found! Description: " & err.description
        Main.HandleError err, MODULE_NAME, "Initialize"
        GoTo CleanExit

End function

I want my macro to stop running when error occurs in some module and not to stop if it's in another module (hence the GoTo CleanExit).

Error handler is set-up in this way:

Public Function HandleError(ByRef err As ErrObject, ByVal moduleOrgin As String, ByVal methodOrgin As String)

    Dim wbk As Workbook

    'Do something if module origin meets my parameters and exit function right here if my conditions are met

    MsgBox "Some message to the user about the problem"

    If GetSetting(SETTING_HIDE_APPLICATION, False) = True Then
        For Each wbk In addinWorkbook.Application.Workbooks
            wbk.Saved = True
        Next wbk

        addinWorkbook.Application.Quit
    End If

End Function

After this code runs I assume that all further code running stops, as my Excel workbook, which hosts my macro code is closed with the application.

In reality I get a cascade of errors, where the error message is shown 3 times until it closes for good. How can I avoid code any code running after Application.Quit method?

Code workflow when error occurs and what runs after Application.Quit:

  1. Main method to initialize my form
  2. Call to loader method which throws error (Application should quit here)
  3. Main method continues after loader method is finished
  4. Subsequent method is called from main method which also throws an error (because first loader failed)
  5. Lastly my main method throws an error

In total I receive 3 msgboxes with error descriptions.

I must note, that I use the same error handling procedure in all methods, but I would like the code to stop executing, so further code does not trigger any errors.

Upvotes: 2

Views: 2156

Answers (1)

Vityata
Vityata

Reputation: 43593

How can I avoid code any code running after Application.Quit method?

If you want to stop everything, write End after Application.Quit. It stops every piece of VBA and kills all variables you have assigned. This is not considered a good practice (At all!), but it will work exactly as you want.

Upvotes: 2

Related Questions