Closing a file that is already open

aziz rasul

Active member
Local time
Today, 23:39
Joined
Jun 26, 2000
Messages
1,935
Is there a way of closing an MS Excel spreadsheet using code?
 
Try using GetObject(). To check if open.
If error occurs, Excel not open.
If no error, obj.Quit
Make refrence to Excel Object library.
 
Tried your suggestion. Many thanks. Using the online help, I have

Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As Long) As Long
Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

Public Sub GetExcel(strFileName As String)

Dim MyXL As Object

Set MyXL = GetObject(, "Excel.Application")

DetectExcel

Set MyXL = GetObject(strFileName)

' MyXL.Application.Visible = True
' MyXL.Parent.Windows(1).Visible = True

MyXL.Application.DisplayAlerts = False
MyXL.Application.Quit

Set MyXL = Nothing

End Sub

Public Sub DetectExcel() ' Procedure detects 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
 

Users who are viewing this thread

Back
Top Bottom