Closing word application from excel vba

前端 未结 3 687
死守一世寂寞
死守一世寂寞 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:14

    Another option is to use Shell to accesss the elegance of powershell

    Sub Comesfast()
    X = Shell("powershell.exe kill -processname winword", 1)
    End Sub
    
    0 讨论(0)
  • 2021-01-21 01:17

    Try the code below, it will close Word Application (without saving).

    Option Explicit
    
    Sub CloseWordWindows()
    
    Dim objWord As Object
    
    On Error Resume Next
    Set objWord = GetObject(, "Word.Application")
    
    ' if no active Word is running >> exit Sub
    If objWord Is Nothing Then
        Exit Sub
    End If
    
    objWord.Quit
    Set objWord = Nothing
    
    End Sub
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题