Excel vba kill an invisible application after an error

Viewed 1251

I have an application that first creates an invisible application:

        Dim ExcelApp As Object
        Set ExcelApp = CreateObject("Excel.Application")
        ExcelApp.Visible = False
        ExcelApp.ScreenUpdating = False
        ExcelApp.DisplayAlerts = False
        ExcelApp.EnableEvents = False

And then proceeds to use it to open files invisibly:

      Do While fileTitle <> ""
          Dim dataWorkbook As Workbook
          Set dataWorkbook = ExcelApp.Application.Workbooks.Open(folderPath & fileTitle)

At the end of the operations with the file macros closes the file:

          dataWorkbook.Close
          fileTitle = Dir()
         Loop

At the end of the sub macros closes the application:

      ExcelApp.Quit
      Set ExcelApp = Nothing
End Sub

However, if an error occurs before the file is closed, the invisible file and the application would never be closed and would continue to linger in operation systems not only eating away the memory and resources, but also preventing from doing any operations with the opened filed - renaming, opening or editting it.

I wonder if there is a way to close both the file and the application if an error occurs - in the current macros or to create a separate macros that detects invisible applications no variable points to and closes it.

2 Answers
Related