Releasing Excel Automation

G

Gary Cobden

Hi

I have a routine that uses VBA to open a hidden occurence of Excel,
and do background computations.

However, when the routine terminates, I have
not been able to find a way of closing this Hidden occurrence. I can
close any foreground instances without any problem, but the same
coding does not work for hidden occurences.

Code as below:-


Function fIsAppRunning(ByVal strAppName As String, _
Optional fActivate As Boolean) As Boolean
Dim lngH As Long, strClassName As String
Dim lngX As Long, lngTmp As Long
Const WM_USER = 1024
On Local Error GoTo fIsAppRunning_Err
fIsAppRunning = False
Select Case LCase$(strAppName)
Case "excel": strClassName = "XLMain"
Case Else: strClassName = vbNullString
End Select

If strClassName = "" Then
lngH = apiFindWindow2(vbNullString, strAppName)
Else
lngH = apiFindWindow2(strClassName, vbNullString)
End If
If lngH <> 0 Then
apiSendMessage lngH, WM_USER + 18, 0, 0
lngX = apiIsIconic(lngH)
If lngX <> 0 Then
lngTmp = apiShowWindow(lngH, SW_SHOWNORMAL)
End If
If fActivate Then
lngTmp = apiSetForegroundWindow(lngH)
End If
fIsAppRunning = True
End If
fIsAppRunning_Exit:
Exit Function
fIsAppRunning_Err:
fIsAppRunning = False
Resume fIsAppRunning_Exit
End Function


Function fCloseApp(lpClassName As String) As Boolean

Dim lngRet As Long, hWnd As Long, pID As Long

hWnd = apiFindWindow(lpClassName, vbNullString)
If (hWnd) Then
lngRet = apiPostMessage(hWnd, WM_CLOSE, 0, ByVal 0&)
Call apiGetWindowThreadProcessId(hWnd, pID)
Call apiWaitForSingleObject(pID, INFINITE)
fCloseApp = Not (apiIsWindow(hWnd) = 0)
End If
End Function

And then, to close the running instance in my process -

Do While fIsAppRunning("excel")
Set xlApp = GetObject(, "Excel.Application")
If xlApp.Visible = True Then
fCloseApp ("XLMain")
End If
Set xlApp = Nothing
Loop

Any help would be appreciated

Thanks

Gary
 
K

Ken Snell [MVP]

I think the problem is in this code block:

Do While fIsAppRunning("excel")
Set xlApp = GetObject(, "Excel.Application")
If xlApp.Visible = True Then
fCloseApp ("XLMain")
End If
Set xlApp = Nothing
Loop


In this code, you set the object variable xlApp to the EXCEL program.
However, you then set it to Nothing without closing the application when
it's invisible. Is that what you want to occur?
 
J

John Nurick

In addition, the hidden instance won't close if there is an unsaved
workbook open. I usually use something like this:

Do While xlApp.Workbooks.Count > 0
xlApp.Workbooks(xlApp.Workbooks.Count).Close False
Loop
xlApp.Quit
Set xlApp = Nothing
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top