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
 

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