If Excel is not open, I want to do nothing.
If Excel is open with another file than "C:\Temp\test.xls",
I want to do nothing.
If Excel is open WITH "C:\Temp\test.xls", I just want to close Excel without saving.
Here is my code, but it open the file even if the file was not already open. Any Help will be appreciate:
If Excel is open with another file than "C:\Temp\test.xls",
I want to do nothing.
If Excel is open WITH "C:\Temp\test.xls", I just want to close Excel without saving.
Here is my code, but it open the file even if the file was not already open. Any Help will be appreciate:
Code:
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
Sub CloseExcel()
Dim MyXL As Object
DetectExcel
'I don't want that the file open.
'If the file is already open, I just want to close it
Set MyXL = GetObject("C:\Temp\test.xls")
MyXL.Application.Visible = True
MyXL.Parent.Windows(1).Visible = True
MyXL.Application.Quit
End Sub
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