Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to close an open file in Excel?

Status
Not open for further replies.

todd666

IS-IT--Management
Dec 3, 2001
61
CA
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:

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
 
Ok,

With the thread you send me, I am able to close the file if the file is open and if no change were made in the file.

But if there are change in the Excel file that was made, I don't want to close the file, I just want to pop up a message that said like "This excel file is open, close it and retry".

How can I "trap" this information that will tell me that the file is open?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top