Closing word application from excel vba

前端 未结 3 688
死守一世寂寞
死守一世寂寞 2021-01-21 00:34

I\'m trying in the beginning of my macro to close all word application if it\'s open, although I don\'t no which documents are open, and I can\'t set them as an object. Thanks.<

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-21 01:28

    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
    

提交回复
热议问题