I am trying to close (2) different Excel instances from Access. I am using the code below but it only allows me close one instance at a time before it produces the error. It can not get the 2nd instance unless I run it again. Why is this happening and how can I write the code to close all the instances without having to rerun the code.
Code:
Public Sub CloseAllExcel()
On Error Resume Next
Dim xlApp As Excel.Application
Dim i As Integer
i = 0
Do While i < 5 'to avoid infinite loop
Set xlApp = Nothing
Set xlApp = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
MsgBox Err
Err.Clear
Exit Do
End If
xlApp.Visible = True
xlApp.ScreenUpdating = True
xlApp.DisplayAlerts = False
xlApp.Workbook.Close False
i = i + 1
xlApp.Quit
xlApp.DisplayAlerts = True
Set xlApp = Nothing
Loop
End Sub