0

I have this access application that converts csv files into excel files and it works 99% of the time. Unfortunately, sometimes it locks up on on file and then it crashes the whole application. Of course each instance of it crashing I want to fix but I also don't want the single file crashing to lock up the whole application. I found out that the excel file is getting locked up in a background process and that needs to be closed before the application can continue. So what I am doing is after converting each file and then closing excel before I start to convert the next file, I test if excel is already open. If it is open, it will ask the user if they have excel open and if they say no, it will close the background process.

This is the code I have and it is correctly testing if excel is open but I cannot figure out how to close the excel application after.

Sub CloseExcelIfOpen()
    
    Dim objList As Object, objType As Object, strObj$
    strObj = "Excel.exe"
    Set objType = GetObject("winmgmts:").ExecQuery("select * from win32_process where name='" & strObj & "'")
    If objType.Count > 0 And IsExcelOpen = ExcelState.NotChecked Then
        IsExcelOpen = MsgBox("Do you have excel open?", vbYesNo)
    End If
    
End Sub
djblois
  • 963
  • 1
  • 17
  • 52
  • Have you tried `GetObject("Excel.Application")` ? – Tim Williams May 03 '23 at 18:46
  • @TimWilliams it says Invalid Syntax when I try running that. – djblois May 03 '23 at 18:51
  • Common topic. One discussion https://www.access-programmers.co.uk/forums/threads/how-to-close-specific-excel-file-from-access.305506/ – June7 May 03 '23 at 19:03
  • 1
    If a single hidden session may exist you can use `Set objType = GetObject(, "Excel.Application")' followd by `It not objType is nothing Then objType.Quit`. Otherwise, use the above code in a iteration of maximum possible number of sessions... – FaneDuru May 03 '23 at 19:20
  • @June7 that link doesn't say how to close the excel application, it says how to close a specific excel workbook – djblois May 03 '23 at 19:50
  • Isn't that the issue - specific file is already open? Multiple Excel app instances can be open. If you are programmatically opening file then need to deal with that. When programmatically opening Excel app and file objects, use Close method to close Excel file object and use Quit method to quit Excel app object. The app object can remain open while files are opened and closed. If Excel is manually opened and you want VBA to close instance of Excel app, that is different issue. What if user running this code has Excel open for other purposes - you want to terminate those instances? – June7 May 03 '23 at 20:28

0 Answers0