If you are using early binding (Dimming your Excel Objects as Excel
objects), I recommend you switch to late binding. That is Dimming them as
Objects. There are a number of reasons for this, and I have found it works
much better.
Below is code I use to open a work book and to close it. There is also a
procedure I think I got from VBA Help called DetectExcel that this code
calls. In any case, I don't have the problem of the Excel process staying
resident anymore. This also allows your code to execute even if the user has
Excel open when they run your code.
Dim xlApp As Object ' Reference to Microsoft Excel.
Dim blnExcelWasNotRunning As Boolean ' Flag for final release.
Dim xlBook As Object 'Workbook Object
Dim xlSheet As Object 'Worksheet Object
On Error Resume Next ' Defer error trapping.
Set xlApp = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
blnExcelWasNotRunning = True
Set xlApp = CreateObject("excel.application")
Else
DetectExcel
End If
Err.Clear ' Clear Err object in case error occurred.
On Error GoTo cmdImport_Click_Error
DoEvents
xlApp.DisplayAlerts = False
xlApp.Interactive = False
xlApp.ScreenUpdating = False
'Open the Workbook
Set xlBook = xlApp.Workbooks.Open(varGetFileName, 0, True)
Set xlSheet = xlBook.Worksheets(1)
'Close the workbook and quit Excel
xlBook.Close
Set xlBook = Nothing
Set xlSheet = Nothing
If blnExcelWasNotRunning = True Then
xlApp.Quit
Else
xlApp.DisplayAlerts = True
xlApp.Interactive = True
xlApp.ScreenUpdating = True
End If
Set xlApp = Nothing
Sub DetectExcel()
' Procedure dectects a running Excel and registers it.
Const WM_USER = 1024
Dim hWnd As Long
' If Excel is running this API call returns its handle.
hWnd = FindWindow("XLMAIN", 0)
If hWnd = 0 Then ' 0 means Excel not running.
Exit Sub
Else
' Excel is running so use the SendMessage API
' function to enter it in the Running Object Table.
SendMessage hWnd, WM_USER + 18, 0, 0
End If
End Sub