# Word VBA to Close Excel Application



## sfpowell (Jul 18, 2011)

I'm using Windows 7 with MS Office 2007 and I have written some VBA code inside MS Word 2007 that performs a Mail Merge with an Excel Workbook. When the program is complete I want the code to close the Excel Application. The code 
	
	
	
	
	
	



```
Excel.Application.ActiveWorkbook.Close False
Excel.Application.Quit
```
 seems to work when Excel was originally opened by the program but it doesn't seem to work when Excel is already open.
Can anyone tell me how I can have the program check to see if Excel is open and if it is, close it?


----------



## John_w (Jul 18, 2011)

Try something like this.  I'm using early binding of the Excel objects, so you need a reference to MS Excel Object library in your Word VBA project.

```
Sub Close_Excel()

    Dim Excel As Excel.Application
    Dim ExcelOpened As Boolean
    
    ExcelOpened = False
    On Error Resume Next
    Set Excel = GetObject(, "Excel.Application")
    If Excel Is Nothing Then
        Set Excel = New Excel.Application
        ExcelOpened = True
    End If
    On Error GoTo 0

    With Excel
        If ExcelOpened Then
            .Visible = True
            .Workbooks.Add
        End If
        .ActiveWorkbook.Close False
        .Quit
    End With
    
End Sub
```


----------



## sfpowell (Jul 19, 2011)

It worked! It's crazy some of the things you have to do to accomplish the simplest of tasks.
Thanks for your help.


----------

