Search code examples
vbaexcel

Closing word application from Excel VBA


I'm trying, at the beginning of my macro, to close all open Word application instances, although I don't know which documents are open, and I can't set them as an object.


Solution

  • This will close all running Word documents.

    You need On Error Resume Next to prevent errors if no Word application instance is running.

    Option Explicit
    
    Sub CloseWordDocuments()
    
        Dim objWord As Object
        
        Do
            On Error Resume Next
            Set objWord = GetObject(, "Word.Application")
            On Error Go To 0
            If Not objWord Is Nothing Then
                objWord.Quit
                Set objWord = Nothing
            End If
        Loop Until objWord Is Nothing
    
    End Sub
    

    Edit

    Correction below because the loop above has a flaw i.e. it will exit after the first instance of Word is closed ...

    Option Explicit
    
    Sub CloseWordDocuments()
    
        Dim objWord As Object
        Dim blnHaveWorkObj As Boolean
    
        ' assume a Word object is there to be quit
        blnHaveWorkObj = True
        
        ' loop until no Word object available
        Do
            On Error Resume Next
            Set objWord = GetObject(, "Word.Application")
            If objWord Is Nothing Then
                ' quit loop
                blnHaveWorkObj = False
            Else
                ' quit Word
                objWord.Quit
                ' clean up
                Set objWord = Nothing
            End If
        Loop Until Not blnHaveWorkObj
    
    End Sub