how to close Word opened by VBA

2

For each Execution of the DeleteSel function, a "WINWORD" is opened in memory, even with the Close command and / or Quit it does not close.

Sub DeleteSel(msg As Outlook.MailItem)
Dim objDoc As Object
Dim objBkm As Object

Set objDoc = CreateObject("Word.Application")

objDoc.Visible = True
objDoc.Activate

On Error Resume Next
Set objDoc = msg.GetInspector.WordEditor
Set objBkm = objDoc.Bookmarks("_MailAutoSig")

If Not objBkm Is Nothing Then
    objBkm.Select
    objDoc.Windows(1).Selection.Delete
End If

objDoc.Close
objBkm.Close
Set objBkm = Nothing
Set objDoc = Nothing
End Sub

Would anyone have any tips?

    
asked by anonymous 24.01.2018 / 12:49

3 answers

1

Use the option below:

objDoc.Quit

Instead of ".Close"

Before "Quit" save what you need to save.

Issue 1

Example

Sub abreWord()

Dim objDoc As Object

Set objDoc = CreateObject("Word.Application")

    objDoc.Visible = True
    objDoc.Activate

    objDoc.Quit

    Set objDoc = Nothing

End Sub

In the above case the word is opened and closed, including the winword process.

I hope I have helped!

    
24.01.2018 / 14:48
1

I found a solution that at least only opens 1 instance of WINWORD in the task manager or uses the one that is already open, since it is not closing with the QUIT command due to the use of Bookmarks (Probably)

Sub DeleteSel(msg As Outlook.MailItem)
    Dim objDoc As Object
    Dim objBkm As Object

    On Error Resume Next
    Set objDoc = GetObject(, "Word.Application")

    If objDoc Is Nothing Then
        Set objDoc = CreateObject("Word.Application")
    End If

    On Error Resume Next
    Set objDoc = msg.GetInspector.WordEditor
    Set objBkm = objDoc.Bookmarks("_MailAutoSig")

    If Not objBkm Is Nothing Then
        objBkm.Select
        objDoc.Windows(1).Selection.Delete
    End If

    objBkm.Quit
    objDoc.Quit
    Set objBkm = Nothing
    Set objDoc = Nothing
End Sub
    
25.01.2018 / 19:56
1

Exit and Set Word Object = Nothing

You create two objDoc with Set objDoc . Then at the end you close only the last while the first one remains open.

A VBA program to close all Word files is as follows:

'https://stackoverflow.com/a/41100852/7690982
Option Explicit

Sub FecharDocWord()

    Dim objWord As Object

    Do
        On Error Resume Next
        Set objWord = GetObject(, "Word.Application")
        If Not objWord Is Nothing Then
            objWord.Quit
            Set objWord = Nothing
        End If
    Loop Until objWord Is Nothing

End Sub

Credits: Robin Mackenzie

Kill the task

To close the processes in the Task Manager.

'http://vbadud.blogspot.com.br/2009/04/how-to-kill-word-process-using-vba.html
Sub Kill_Word()

Dim sKillWord As String 

sKillWord = "TASKKILL /F /IM Winword.exe" 

Shell sKillWord, vbHide 

End Sub
Read more at http://vbadud.blogspot.com/2009/04/how-to-kill-word-process-using-vba.html#yWeSjbJsIeyDBDDv.99
    
24.01.2018 / 19:55