You should also investigate the root cause behind the failure. Perhaps it fails before it actually closes the Excel instance?
Also, you might as well continue with the flow even if the Excel process is running. As noted, some Excel processes continue running after closing the document. This simply means the app itself has not stopped yet, but the document is closed, meaning it should not affect any further actions in your flow whatsoever. You can thus continue, regardless of whether the process is running or not.
You can also check if the specific Excel instance is alive or not by checking the handle on the instance variable.
If %ExcelInstance.Handle% is not empty (can only be empty before opening Excel) and is not equal to 0, the Excel instance is alive. If it is equal to 0, the instance has successfully been closed, meaning the document is no longer open.
We usually do it as follows:
IF the instance is alive, we give it up to 5 seconds for the process to stop.
If it then does not stop, we run a PowerShell script to close the Excel app:
$excel = [Runtime.Interopservices.Marshal]::GetActiveObject('Excel.Application')
$excel.Visible = $false
$excel.DisplayAlerts = $false
$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
Remove-Variable -Name Excel
[GC]::Collect()
[GC]::WaitForPendingFinalizers()
if ($excel.Workbooks.Count -eq 0)
{
Stop-Process -Name EXCEL -ErrorAction SilentlyContinue
}
If this still does not close all Excel processes, then we terminate it.