Word application on close

There are two basic ways to capture when any Word document closes:

  1. Use a macro named AutoClose in any module of Normal.dotm (or any template loaded as an add-in). This is the «old-fashioned» way that comes from the WordBasic (Word 2.0 and 6.0) days.

Note that if any other document (or template) has AutoClose that this will over-ride the macro running a «more general» level. In other words, the document- (or template-) specific code takes priority.

Sub AutoClose()
  MsgBox "The document " & ActiveDocument.FullName & " is closing."
End Sub
  1. Work with an application-level event. This requires both a class module and a «plain» module. The event code is in the class module; the code to initialize the class must be in a «plain» module.

This event’s name is DocumentBeforeClose and can be cancelled, both by the user and by code (see the Cancel parameter in the event signature).

In contrast to AutoClose, if more than one document or template has the event running all will fire — there is no priority or «override».

Class module named clsEvents

Public WithEvents app As Word.Application

Private Sub app_DocumentBeforeClose(ByVal Doc As Document, Cancel As Boolean)
  MsgBox "The document " & Doc.FullName & " is being closed."
End Sub

Module

Public myEvents As New clsEvents

Public Sub StartEvents()
    Set myEvents.app = Word.Application
End Sub

Public Sub EndEvents()
    Set myEvents.app = Nothing
End Sub

Note that if both types of event are present the AutoClose fires after DocumentBeforeClose.

Note also that there is a document-specific event that will fire only for that document: Document_Close. This event must be in the ThisDocument class module of that document.

Private Sub Document_Close()

End Sub

  • Remove From My Forums
  • Question

  • In my Word add-in I start process to read text. But I want to kill ths process when user close MS Word. How to do this in C#?

Answers

  • Hello Lenkita,

    The Process class provides the
    Kill method which is used for immediately stopping the associated process. Note, the
    Kill method executes asynchronously. After calling the
    Kill method, call the WaitForExit method to wait for the process to exit, or check the
    HasExited property to determine if the process has exited.

    Also you can use the CloseMainWindow method. Here is what MSDN states:

    Kill forces a termination of the process, while
    CloseMainWindow only requests a termination. When a process with a graphical interface is executing, its message loop
    is in a wait state. The message loop executes every time a Windows message is sent to the process by the operating system. Calling
    CloseMainWindow sends a request to close to the main window, which, in a well-formed application, closes child windows
    and revokes all running message loops for the application. The request to exit the process by calling
    CloseMainWindow does not force the application to quit. The application can ask for user verification before quitting,
    or it can refuse to quit. To force the application to quit, use the
    Kill method. The behavior of
    CloseMainWindow is identical to that of a user closing an application’s main window using the system menu. Therefore,
    the request to exit the process by closing the main window does not force the application to quit immediately.

    try
    {
        Process myProcess;
        myProcess = Process.Start("Notepad.exe");
        // Display physical memory usage 5 times at intervals of 2 seconds. 
        for (int i = 0;i < 5; i++)
        {
            if (!myProcess.HasExited)
            {
               // Discard cached information about the process.
               myProcess.Refresh();
               // Print working set to console.
               Console.WriteLine("Physical Memory Usage: " + myProcess.WorkingSet.ToString());
               // Wait 2 seconds.
               Thread.Sleep(2000);
            }
            else {
               break;
            } 
       }
    
        // Close process by sending a close message to its main window.
        myProcess.CloseMainWindow();
        // Free resources associated with process.
        myProcess.Close();
    
    }
    catch(Exception e)
    {
        Console.WriteLine("The following exception was raised: ");
        Console.WriteLine(e.Message);
    }
    
    

    • Marked as answer by

      Monday, April 7, 2014 7:00 AM

Please Note:
This article is written for users of the following Microsoft Word versions: 97, 2000, 2002, and 2003. If you are using a later version (Word 2007 or later), this tip may not work for you. For a version of this tip written specifically for later versions of Word, click here: Keeping Word Open after Closing Documents.

Written by Allen Wyatt (last updated April 21, 2018)
This tip applies to Word 97, 2000, 2002, and 2003


Paul notes that in Excel he can close all workbooks and the application still remains active. He would like to be able to close all the documents in Word and have the program still remain open, as well. He wonders if there is some way to configure Word to behave in this way.

How the Word program behaves when you close the last document can vary, depending on your version of Word. That it, it varies if you use the Close button in the upper-right corner of the screen to close your documents.

If you want to make sure that the program remains open after closing all documents, you should make sure that you should click the document Close button instead of the program Close button. You can tell the difference between the two because the program Close button has a 3-D appearance while the document Close button does not. In addition, the document Close button is located lower on the screen than the program Close button. Click the document Close button, and the program window should remain open whether it contains documents or not.

You can also choose to close documents by using one of two shortcuts: either Ctrl+W or Ctrl+F4. Using either one is the same as clicking on the document Close button. When the last document is open and you use one of these shortcuts, the document is closed, but the program window remains open.

WordTips is your source for cost-effective Microsoft Word training.
(Microsoft Word is the most popular word processing software in the world.)
This tip (9989) applies to Microsoft Word 97, 2000, 2002, and 2003. You can find a version of this tip for the ribbon interface of Word (Word 2007 and later) here: Keeping Word Open after Closing Documents.

Author Bio

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. Learn more about Allen…

MORE FROM ALLEN

Using the Copy or Move Text Keys

Most people use the Clipboard to copy and move text in Word. Before the Clipboard, Word used F2 to move text and Shift+F2 …

Discover More

Renaming a Workbook

Renaming a workbook from within Excel can seem daunting, but it is actually quite easy. All you need to do is use the …

Discover More

Word 2010 Styles and Templates (Table of Contents)

Styles are at the heart of Word’s formatting power. Understanding how to use styles can greatly increase your ability to …

Discover More

More WordTips (menu)

Reducing Word’s CPU Load

A series of options for checking the CPU load of your Word document.

Discover More

Automatically Updating Fields and Links

You can update fields and links automatically when you print your document, but what if you want them updated when you …

Discover More

Changing the Company Name

When you install Office or Word, you are asked for your company’s name as part of the installation process. If you later …

Discover More

natawka

0 / 0 / 0

Регистрация: 07.11.2010

Сообщений: 23

1

21.06.2016, 22:07. Показов 4543. Ответов 6

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Помогите решить такую проблему, бьюсь уже далеко не первый день.
Нужно, чтобы при закрытии: 1) документа; 2) оболочки Word срабатывало событие у Application таких процедур как: «Private Sub appWord_DocumentBeforeClose» и «appWord_Quit». Эти события у меня находятся в моем шаблоне, прописанные в созданном классе.
Работа должна происходить следующим образом. В Word есть некий файл, через него я запускаю и подключаю свой шаблон с макросами. На стартовой форме, перед подключением моего шаблона, если юзер выбирает кнопку ОК, шаблон подключается и инициируется событие «Public WithEvents appWord As Word.Application» для процедур: «Private Sub appWord_DocumentBeforeClose» и «Private Sub appWord_Quit».
Моя задача следующая:
1) В процедуре «Private Sub appWord_DocumentBeforeClose» прописана проверка на имя файла, чтобы для определенного документа запускалась специальная форма и в зависимости от выбора юзера этот документ либо закрывается после отработки с пользователем действий, либо закрытие документа приостанавливается, чтобы юзер сам произвел свои манипуляции с документом. Т.е. полученный результат приводит в «Cancel = True».
2) В процедуре «Private Sub appWord_Quit» прописано, чтобы мой шаблон удалялся из списка подключенных шаблонов и надстроек, потому что оболочка Word полностью закрывается.
3) В шаблоне у меня так же имеется моя кнопка, выведенная на моей отдельной вкладке на ленте для закрытия любого активного документа, чтобы не закрывать всю оболочку Word. В моем коде я делаю закрытие документа, если юзер в MsgBox выбирает закрыть документ.
При старте, когда событие Application для процедур: «Private Sub appWord_DocumentBeforeClose» и «Private Sub appWord_Quit» проинициировано, если закрытие документа использовать стандартным способом или же использовать стандартное нажатие в Word сочетание славишь «Ctr+W», событие работает каждый раз независимо от того сколько раз была попытка прервать работу с формой, а затем производить закрытие тем же самым стандартным способом. НО стоит воспользоваться кнопкой с панели, то событие после первого срабатывания перестает срабатывать в дальнейшем, если юзер прерывает работу формы, а затем вторично закрывает документ уже любым перечисленным мной способом.
Я не понимаю почему событие перестает срабатывать в дальнейшем после первого раза???
Т.е. код перестает срабатывать, событие игнорируется, документ просто закрывается, а при закрытии всей оболочки Word шаблон перестает удаляться из списка подключенных:

Кликните здесь для просмотра всего текста

Visual Basic
1
2
3
4
5
6
Public D As New EventClassModule
 
'Для инициирования переменной, чтобы была возможность прервать закрытие документа
Function InitializationEvents()
  Set D.appWord = Word.Application
End Function



0



5561 / 1367 / 150

Регистрация: 08.02.2009

Сообщений: 4,107

Записей в блоге: 30

22.06.2016, 02:18

2

Вот так да! Вундеркинд в студии.

Браво, natawka! Лучший вопрос всех русскоязычных вордистов. Ставлю 5 звёзд.



1



1068 / 106 / 4

Регистрация: 19.12.2012

Сообщений: 449

22.06.2016, 11:30

3

Не понятна ситуация в вашем вопросе:
— НО стоит воспользоваться кнопкой с панели, то событие после первого срабатывания перестает срабатывать в
дальнейшем
или
— событие после первого срабатывания перестает срабатывать в дальнейшем, если юзер прерывает работу формы, а затем вторично закрывает документ уже любым перечисленным мной способом.

В любом случае, при отработке события в экземпляре класса, попробуйте создавать новый экземпляр, а старый при этом удалять приравнивая его ссылку на Nothing (где они у вас лежат? — как вариант — складывайте их в коллекцию). Конечно не факт, что старый экземпляр сдохнет, но вам-то что с того, что будет утечка лишних 2 кб. памяти?! )
Не видя весь код есть вероятность, что при вызове события закрытия происходит отвязка (почему-то) события от функций класса.

Если совет не соответствует картине, то без кода сложно дать ответ более точный.



0



natawka

0 / 0 / 0

Регистрация: 07.11.2010

Сообщений: 23

22.06.2016, 18:43

 [ТС]

4

Цитата
Сообщение от StepInLik
Посмотреть сообщение

В любом случае, при отработке события в экземпляре класса, попробуйте создавать новый экземпляр, а старый при этом удалять приравнивая его ссылку на Nothing

Если я правильно понимаю Ваш совет, повторно проинициировать в процедуре Private Sub appWord_DocumentBeforeClose после того как

Cancel = True

, то этот вариант не прокатывает, не получается.

Не понятна ситуация в вашем вопросе:
— НО стоит воспользоваться кнопкой с панели, то событие после первого срабатывания перестает срабатывать в
дальнейшем
или
— событие после первого срабатывания перестает срабатывать в дальнейшем, если юзер прерывает работу формы, а затем вторично закрывает документ уже любым перечисленным мной способом.

Как я уже говорила раньше, событие срабатывает хорошо и всегда, только когда документ закрывается по нажатию «Х» на самой оболочке или же «Ctrl+W».

Кликните здесь для просмотра всего текста

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
Public WithEvents appWord As Word.Application
 
Private Sub appWord_DocumentBeforeClose(ByVal Doc As Document, Cancel As Boolean)
  Dim objWordDoc As Word.Document
  Dim strActDocName As String 'имя активного документа
  Dim objPrOrgNovProj As Object 'проект
  Dim strFileName As String 'имя файла проекта
'Стандарт для обнаружения ошибок
On Error GoTo ErrNumber
'==============================================
  strActDocName = ActiveDocument.Name
  Set objWordDoc = Documents.Item(strActDocName)
  If objWordDoc.ProtectionType <> wdNoProtection Then 'если активный док.защищен от редактирования
    Set objWordDoc = Nothing
    Exit Sub
  End If
'Проверка существования проекта файла
  Set objPrOrgProj = GetObjectPrOrgProj(strFN)
  If objPrOrgProj Is Nothing Then 'если проект не существует
    Set objWordDoc = Nothing
    Exit Sub
  Else 'если проект существует
    strFileName = objPrOrgProj.Name
    If (objWordDoc.Name <> strFileName) Then 'если имя файла другое
      Set objWordDoc = Nothing
      Set objPrOrgProj = Nothing
      Exit Sub
    Else
      ЗапускФормы
      If GetResult = True Then 'если юзер нажал "Отмена" или "Х" на форме
        Cancel = True
      Else 'если юзер нажал «Esc» на форме
        ...
      End If
    End If
  End If
'==============================================
ExitHere:
'Очистить объекты
  Set objWordDoc = Nothing
  Set objPrinOrgPoNovProj = Nothing
Exit Sub
 
ErrNumber:
  Select Case Err.Number
    Case 4248 'Данная команда недоступна, т.к. не открыт ни один документ
      Resume ExitHere
    Case Else
      MsgBox Err.Description, vbCritical, "«AppWord_DocumentBeforeClose». Ошибка № " & Err.Number
      Resume ExitHere
  End Select
End Sub

Но событие срабатывает только 1 раз, если использовать макрос на кнопке, которая выведена у меня на моей вкладке. И уже в дальнейшем что Ctrl+W, что «Х» на самой оболочке, что по кнопке — событие больше уже не срабатывает. В коде на кнопку при закрытии у меня нет ничего криминального:

Кликните здесь для просмотра всего текста

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
Private Sub ЗакрытьДок()
  Dim objWordDoc As Word.Document
  Dim strDocName As String
  Dim intMsgBx As Integer
 
On Error GoTo ErrNumber
'==============================================
  If Application.Documents.Count = 0 Then Exit Sub 'Если не открыто ни одного документа
    strDocName = ActiveDocument.Name
    Set objWordDoc = Documents.Item(strDocName)
    intMsgBx = MsgBox("Закрыть документ?" & vbCrLf & "«" & strDocName & "»", _
                      vbQuestion + vbOKCancel, "Info")
'Вычисляем, что конкретно нажал юзер?
    If intMsgBx = 1 Then 'если юзер нажал "Да"
'Проверка, если юзер сделал изменения
      If objWordDoc.Saved = True Then 'юзер ничего не изменял
        objWordDoc.Close 'SaveChanges:=wdSaveChanges
      Else 'юзер внес изменения
'Запуск макроса MS Word на закрытие документа с запросом на сохранить изменения: да/нет/отмена
        Application.Run "DocClose" 'чтобы ошибка (4198) не возникала
      End If
    ElseIf intMsgBx = 2 Then 'если юзер нажал "Отмена"
      Exit Sub
    End If
'==============================================
ExitHere:
  Set objWordDoc = Nothing
Exit Sub
 
ErrNumber:
  Select Case Err.Number
    Case -2147352573 'Метод или св-во недоступны, поскольку документ является защищенным.
      On Error GoTo 0
      Set objWordDoc = Nothing
      ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges, OriginalFormat:=wdPromptUser
      End
    Case 91 'Ошибка: "Object variable or With block variable not set"
      On Error GoTo 0
      Set objWordDoc = Nothing
      End
    Case 4198 '"Ошибка команды" - если нажать отмена в сообщении о сохранении изменений в шаблон
      On Error GoTo 0
      Set objWordDoc = Nothing
      End
    Case 4248 'Данная команда недоступна, т.к. не открыт ни один документ
      Resume ExitHere
    Case 4605 'Метод или свойство недоступны, поскольку объект ссылается на защищенную область документа
      On Error GoTo 0
      Set objWordDoc = Nothing
      ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges, OriginalFormat:=wdPromptUser
      End
    Case Else
      MsgBox Err.Description, vbCritical, "«ЗакрытьДок». Ошибка № " & Err.Number
      Resume ExitHere
  End Select
End Sub



0



StepInLik

1068 / 106 / 4

Регистрация: 19.12.2012

Сообщений: 449

23.06.2016, 10:40

5

Вы писали, что где-то используете код:

Visual Basic
1
2
3
4
5
6
Public D As New EventClassModule
 
'Для инициирования переменной, чтобы была возможность прервать закрытие документа
Function InitializationEvents()
  Set D.appWord = Word.Application
End Function

так и добавьте в класс и в код функции обработчика кнопки пересоздание экземпляра класса (ниже код только для класса, для кнопки допишите сами(но в конце всех работ функции):
(немного подправил ваш класс, частично изменив и нотацию (посмотрите, возможно что-то возьмете на вооружение):

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
Public WithEvents appWord As Word.Application
 
Private Sub appWord_DocumentBeforeClose(ByVal Doc As Document, Cancel As Boolean)
 Dim objWordDoc As Word.Document
 Dim strActDocName As String        ' имя активного документа
 Dim objPrOrgNovProj As Object      ' проект
 Dim strFileName As String          ' имя файла проекта
 
On Error GoTo ErrHandl
 
 '---> Обработка
 strActDocName = ActiveDocument.Name
 Set objWordDoc = Documents.Item(strActDocName)
 If objWordDoc.ProtectionType = wdNoProtection Then 'активный документ НЕ защищен от редактирования
  Set objPrOrgProj = GetObjectPrOrgProj(strFN)
  
  If Not objPrOrgProj Is Nothing Then        'если проект существует
    strFileName = objPrOrgProj.Name
    If objWordDoc.Name = strFileName Then    'если имя файла другое
      ЗапускФормы
      If GetResult = True Then               'если юзер нажал "Отмена" или "Х" на форме
        Cancel = True
      Else                                   'если юзер нажал «Esc» на форме
        ...
      End If
    End If
  End If
 End If
 '---< Обработка
 
 On Error Resume Next
 Set objWordDoc = Nothing: Set objPrinOrgPoNovProj = Nothing
 Set D = New EventClassModule
 Set D.appWord = Word.Application
 
Exit Sub
ErrHandl:
 Select Case Err.Number
  Case 4248     ' команда недоступна, т.к. не открыт ни один документ
 Case Else
  MsgBox Err.Description, vbCritical, """AppWord_DocumentBeforeClose"". Ошибка № " & Err.Number
 End Select
 
 On Error Resume Next
 Set objWordDoc = Nothing: Set objPrinOrgPoNovProj = Nothing
 Set D = New EventClassModule
 Set D.appWord = Word.Application
End Sub

Попробуйте и напишите что у вас получилось.



1



0 / 0 / 0

Регистрация: 07.11.2010

Сообщений: 23

23.06.2016, 14:39

 [ТС]

6

Цитата
Сообщение от StepInLik
Посмотреть сообщение

так и добавьте в класс и в код функции обработчика кнопки пересоздание экземпляра класса (ниже код только для класса, для кнопки допишите сами(но в конце всех работ функции):
(немного подправил ваш класс, частично изменив и нотацию (посмотрите, возможно что-то возьмете на вооружение)

Попробовала Ваш вариант, вот что получается. Если в конце делать пересоздание экземпляра класса, как Вы посоветовали, то при нажатии на форме кнопки, которая должна прерывать выполнение на закрытие документа, происходит цикл и форма перезапускается по новой и так до бесконечности, если не нажать другую кнопку на форме.
Но все равно спасибо за идею.
В итоге вышла из положения другим путем. Перенесла из своей процедуры на закрытие документа свой MsgBox в процедуру «Private Sub appWord_DocumentBeforeClose», таким образом мой макрос на закрытие стал больше мне не нужен. А на свою вкладку вывела в замен своего макроса уже стандартную кнопку на закрытие документа. Соответственно получается, что процедура «Private Sub appWord_DocumentBeforeClose» теперь срабатывает из оболочки Word со всех возможных сторон всегда.
Хотя вопрос, почему из моей непосредственно процедуры событие перестает срабатывать в дальнейшем после первого раза отработки — для меня остался загадкой. Не понятно, что именно заставляет при стандартном закрытии документа у майкрософта в Word держать событие, если так можно выразиться простым языком?
Нет, ну еще конечно возможен вариант, что майкрософт тоже где-то что-то перенамудрил для таких сложных ситуаций, а более подробных примеров с справке у него к сожалению нет.



0



1068 / 106 / 4

Регистрация: 19.12.2012

Сообщений: 449

24.06.2016, 17:10

7

Если честно, то не понятно практически ничего из того, что вы описываете.

Цитата
Сообщение от natawka
Посмотреть сообщение

то при нажатии на форме кнопки, которая должна прерывать выполнение на закрытие документа, происходит цикл и форма перезапускается по новой и так до бесконечности

Ерунда какая-то. Какой у вас происходит цикл?! У вас форма вновь открывается на какое событие? В конструкторе? с чего у вас происходит генерация каких-то событий и действий на создание экземпляра класса?
Вы же не показываете всего кода, а так понять что у вас происходит — очень сложно.

… Word не держит событие. Если это косяк не ваш, то (насколько мне представляется ситуация ваших проблем из того что удалось понять) — это косяк ворда.
В следующий раз старайтесь выкладывать код полностью ((сделаю предположение)даже если вы работаете в софтверной компании).



0



  1. 06-11-2008, 08:41 AM


    #1

    Solved: Running macro on word document close, stopping close

    I am trying to put some data checking into a word document to check for a formfield value, and if the formfield is empty, but only on document close

    with the warning I need it to prompt the user, and to not allow closure of the document until this field is filled in.

    I have the code to do the check, and to give the warning message, but don’t know how to stop closing the document.

    Here’s what I have:

    [vba]Private Sub Document_Close()

    With ActiveDocument
    If .FormFields(«chkMale»).CheckBox.Value = False And _
    .FormFields(«chkFemale»).CheckBox.Value = False Then
    MsgBox «Please say what gender this person is», vbInformation, «~Missing Info~»
    Exit Sub ‘I thought this would do it, but obviously not
    Else
    MsgBox «‘Tis Fine!»,vbinformation,»Title»
    End If
    End With

    End Sub[/vba]

    Last edited by OTWarrior; 06-12-2008 at 01:42 AM.

    Reason: spelling in title

    -Once my PC stopped working, so I kicked it……Then it started working again


  2. 06-11-2008, 09:22 AM


    #2

    Use DocClose.
    [vba]
    Sub DocClose()
    Dim response
    response = MsgBox(«Yes or no», vbYesNo)
    If response = vbYes Then
    ActiveDocument.Close
    Else
    MsgBox «Sorry…I am not going to close the document.»
    Exit Sub
    End If
    End Sub

    [/vba]Neither File > Close, OR the «X» Close button, will close the document unless you click «Yes.»

    Please use the underscore character when posting code. Thanks.


  3. 06-12-2008, 01:51 AM


    #3

    Unfortunately, DocClose doesn’t fire on the close event (or it doesn’t on my pc, word 2003 if that helps).

    If I call your code from within document_close, it does still close not matter which option I choose

    Thanks for the help though.

    ps: sorry about the long line, I have amended it

    -Once my PC stopped working, so I kicked it……Then it started working again


  4. 06-12-2008, 07:25 AM


    #4

    I have figured out that you can stop word from closing using ctrl+break, but when I used it in the code, it doesn’t always fire. it has more chance to fire if there is a «Stop» command before it.

    [VBA]Private Sub Document_Close()
    Dim response
    response = MsgBox(«Yes or no», vbYesNo)
    If response = vbNo Then
    MsgBox «Sorry…I am not going to close the document.»
    Else
    End If
    Stop
    SendKeys «^({BREAK})»
    End Sub[/VBA]

    Alas; this still does not fix it, but is one step closer I feel.

    -Once my PC stopped working, so I kicked it……Then it started working again


  5. 06-12-2008, 09:58 AM


    #5

    How interesting. It works for me. With DocClose, if I click the «X» button, OR File > Close I get the message, and if I do not click Yes, it does NOT close.

    Hmmmm.

    «If I call your code from within document_close, it does still close not matter which option I choose»

    But I do NOT call it from Document_Close. It will not work from Document_Close. That is a completely separate event. It has to be an independent Sub in a standard module.


  6. 06-12-2008, 10:02 AM


    #6

    Just to reiterate, you are using:

    Private Sub Document_Close()

    Mine is (and I posted it as such):

    Sub DocClose()

    They are NOT the same. DocClose is the final closing routine, so it is THERE that you want your stuff.

    If you execute instructions in Document_Close, the «normal» (built-in) instructions in DocClose will still execute. You must overwrite DocClose itself.


  7. 06-13-2008, 12:30 AM


    #7

    I copied your code exactly as you posted it, and tried it in both ThisDocument and a standard module, and it will not execute.

    What am I doing wrong? Does it need to go into a particular place?

    -Once my PC stopped working, so I kicked it……Then it started working again


  8. 06-13-2008, 01:15 AM


    #8

    I just tried all the close methods, and it only fires on my computer when you close the document using the «X» menu button, not word. When it does fire from here, it works perfectly.

    Now I need to figure out how fire it when word closes, not just the document.

    Thanks for your help, I appreciate it

    Last edited by OTWarrior; 06-13-2008 at 01:25 AM.

    Reason: sudden revelation

    -Once my PC stopped working, so I kicked it……Then it started working again


  9. 06-13-2008, 08:58 AM


    #9

    Excuse me, but you wrote:

    «only on document close»

    You never mentioned closing Word itself. Your initial code was using Document_Close…again, not Word itself.

    Hmmm, I think you will have to use WithEvents…I think. Let me check it out.

    Hmmmm…no luck so far. I made a Class, and tried using Quit to intercept closing Word itself, but I can not (so far) make it work the way you want. Tony? Steve?


  10. 06-13-2008, 09:55 AM


    #10

    Quote Originally Posted by fumei

    Hmmmm…no luck so far. I made a Class, and tried using Quit to intercept closing Word itself, but I can not (so far) make it work the way you want. Tony? Steve?

    Hi Gerry,

    Is it ok if it is me….? Been a long time my friend!

    Hi OT,

    The answer to your problem is making use of Word Application Events. Some of these events have a Cancel parameter.

    For your particular case you can use the DocumentBeforeClose application event.

    To use application events do the following:
    a. In your project add a new Class module.
    b. Rename the module to (for instance): oAppClass
    b. In this module paste the following code:
    [VBA]
    Option Explicit
    Public WithEvents oApp As Word.Application
    Private Sub oApp_DocumentBeforeClose(ByVal Doc As Document, Cancel As Boolean)
    Dim response As Integer
    response = MsgBox(«Close, Yes or no?», vbYesNo + vbQuestion)

    If response <> vbYes Then
    Cancel = True
    MsgBox «Sorry…I am not going to close the document.»
    End If
    End Sub

    [/VBA]
    c. This class needs to be instantiated so add a new (normal) module.
    d. in this module paste the following code:
    [VBA]
    Option Explicit
    Dim oAppClass As New oAppClass
    Public Sub AutoOpen()
    Set oAppClass.oApp = Word.Application
    End Sub

    [/VBA]

    Save the lot close and reopen to test.
    I’ve added a sample file as attachment for you to test.

    HTH

    _________
    Groetjes,

    Joost Verdaasdonk
    M.O.S. Master

    Mark your thread solved, when it has been, by hitting the Thread Tools dropdown at the top of the thread.

    (I don’t answer questions asked through E-mail or PM’s)


  11. 06-13-2008, 10:21 AM


    #11

    Of course MOS! You beat me to it. Just came up with that myself.


  12. 06-13-2008, 11:03 AM


    #12

    Quote Originally Posted by fumei

    Of course MOS! You beat me to it. Just came up with that myself.

    Of course you would Gerry, it was a case of specifications!

    _________
    Groetjes,

    Joost Verdaasdonk
    M.O.S. Master

    Mark your thread solved, when it has been, by hitting the Thread Tools dropdown at the top of the thread.

    (I don’t answer questions asked through E-mail or PM’s)


  13. 06-13-2008, 11:25 AM


    #13

    Hi Joost, about time you raised your ugly antlers around here……good to see you. Of course this couldn’t be just a simple fix as «Word is different»

    Steve
    «Nearly all men can stand adversity, but if you want to test a man’s character, give him power.»
    -Abraham Lincoln


  14. 06-13-2008, 11:46 AM


    #14

    Hi Steve,

    Nice to see you haven’t lost your touch! (thanks for the nudge)

    Quote Originally Posted by lucas

    «Word is different»

    Just like me Steve… just like me

    _________
    Groetjes,

    Joost Verdaasdonk
    M.O.S. Master

    Mark your thread solved, when it has been, by hitting the Thread Tools dropdown at the top of the thread.

    (I don’t answer questions asked through E-mail or PM’s)


  15. 06-13-2008, 11:59 PM


    #15

    b. Rename the module to (for instance): oAppClass

    This code looks great but apparently I have never had occasion to rename a Word module. Perhaps, others are abit behind as well. I’m sure it’s easy but I can’t seem to rename a module and trial the code… and the code doesn’t work if you don’t. I’m sure We would appreciate some more comments and learning if you have abit more time. Dave


  16. 06-14-2008, 07:43 AM


    #16

    Quote Originally Posted by Dave

    This code looks great but apparently I have never had occasion to rename a Word module.

    Hi Dave,

    Sure, after you’ve inserted the module (menu insert):
    a. Just select that module
    b. Call the properties screen (F4)
    c. In there it has a name property you can change.

    HTH

    _________
    Groetjes,

    Joost Verdaasdonk
    M.O.S. Master

    Mark your thread solved, when it has been, by hitting the Thread Tools dropdown at the top of the thread.

    (I don’t answer questions asked through E-mail or PM’s)


  17. 06-16-2008, 12:19 AM


    #17

    Wow, lots of responses…thanks guys, you have been a tremendious help.

    Sorry about the confusion Fumei, I asumed that when you close word, word will fire a «close document» type of proceedure. The Users of this document aren’t very technically inclinded, so I should have been clearer with what I wanted, but thank you for the help.

    Your code worked perfectly Mos Master (I only tried adding it to my document, and it it flawless) so thanks for your time with this. I will now close the thread

    -Once my PC stopped working, so I kicked it……Then it started working again


  18. 06-16-2008, 02:08 AM


    #18

    Quote Originally Posted by OTWarrior

    Your code worked perfectly Mos Master (I only tried adding it to my document, and it it flawless) so thanks for your time with this. I will now close the thread

    Hi OT,

    Your welcome, glad I could help!

    _________
    Groetjes,

    Joost Verdaasdonk
    M.O.S. Master

    Mark your thread solved, when it has been, by hitting the Thread Tools dropdown at the top of the thread.

    (I don’t answer questions asked through E-mail or PM’s)


  19. 10-13-2008, 12:18 PM


    #19

    Thank you for sharing!

    I’ve been beating my head on the wall for an hour trying to figure out how to do this… I’ve never coded anything in VB and my job needed a way to remind people to update the document properties and version history in MS Word. I knew it could be done and this definately helps get me started down the right path.

    Again, Thanks


  20. 08-14-2014, 09:28 PM


    #20

    Dear MOS MASTER thank you for this code. You have helped me so much !!!


Image of Susan Harkins

on

March 17, 2011, 12:57 AM PDT

How to automatically execute a Word macro when you create, open, or close a document

By adding a macro to a template’s New, Open, and Close event procedures, you can automate a number of tasks, making you more efficient and productive.

You probably know that you can reduce the amount of time you spend formatting documents by making those format changes to your template, but did you know that you can add macros to a template? You’d do so to automate a regular task in all documents based on the template. Specifically, you can add macros to a template that run when you create a new document or open and close an existing document (based on the template).

Automate a task when creating a new document
To create a new document, you click New, press [Ctrl]+N, or choose New from the File menu/tab. You can get Word to execute a task when you create a new document using the Document_New event procedure, as follows:

  1. Open the template. You’ll find normal.dot or normal.dotm in the Documents and SettingsAdministrator/userApplication DataMicrosoftTemplates folder. You can use any template, not just normal.dot or normal.dotm.
  2. Launch the Visual Basic Editor (VBE) by pressing [Alt]+F11.
  3. In the Project Explorer, double-click ThisDocument.
  4. In the resulting module, enter the event procedure shown below.
  5. Click Save and close the VBE.
Private Sub Document_New()
  'Greet user.
  MsgBox "Greetings", vbOKOnly, "Greetings"
End Sub

When you return to Word, close the template file. Then, create a new document. Word will open a new blank document and display a simple greeting in a message box. Click OK to close the message. (The macro is simple on purpose as this technique is about the event procedure and its relationship to a template. What the macro does isn’t important to the technique.)

Automate a task when opening an existing document
You can automate a task when opening an existing document in much the same way. The only thing that changes is the event procedure. In this case, you’d use the following Document_Open event:

Private Sub Document_Open()
  'Greet user.
  MsgBox "Greetings", vbOKOnly, "Greetings"
End Sub

You can apply this macro to a template or to an existing document. If you add this macro to the template, Word will save it with every new document you create. In other words, every document you create (based on that template) will execute this macro every time you open it.

Automate a task when closing an existing document
I have one last event procedure to cover – one that automates a task when you close a document. Like the last macro, if you add the macro to a template, Word will execute the macro every time you  close any document based on the template. Use the following event procedure:

Private Sub Document_Close()
  'Greet user.
  MsgBox "Greetings", vbOKOnly, "Greetings"
End Sub

Automating a task for all documents by adding it to the template could make you more efficient!

  • Software

title keywords f1_keywords ms.prod api_name ms.assetid ms.date

Application.Quit Method (Word)

vbawd10.chm158336081

vbawd10.chm158336081

word

Word.Application.Quit

0279d848-a8b7-dac7-1e84-a55c72789e3b

06/08/2017

Application.Quit Method (Word)

Quits Microsoft Word and optionally saves or routes the open documents.

Syntax

expression . Quit( SaveChanges , Format , RouteDocument )

expression Required. A variable that represents an Application object.

Parameters

Name Required/Optional Data Type Description
SaveChanges Optional Variant Specifies whether Word saves changed documents before closing. Can be one of the WdSaveOptions constants.
OriginalFormat Optional Variant Specifies the way Word saves documents whose original format was not Word Document format. Can be one of the WdOriginalFormat constants.
RouteDocument Optional Variant True to route the document to the next recipient. If the document does not have a routing slip attached, this argument is ignored.

Example

This example closes Word and prompts the user to save each document that has changed since it was last saved.

Application.Quit SaveChanges:=wdPromptToSaveChanges

This example prompts the user to save all documents. If the user clicks Yes, all documents are saved in the Word format before Word closes.

Dim intResponse As Integer 
 
intResponse = _ 
 MsgBox("Do you want to save all documents?", vbYesNo) 
If intResponse = vbYes Then Application.Quit _ 
 SaveChanges:=wdSaveChanges, OriginalFormat:=wdWordDocument

See also

Concepts

Application Object

Word COM on Close event capture
Topic is solved

Stavencross

Posts: 90
Joined: 24 May 2016, 16:42

Word COM on Close event capture

I’m trying to pop up a message box when the word app is closed, but I can’t seem to figure out what the event is named. If possible, I’d also like to figure out how to pop up a message box when the doc has been saved.

Code: Select all

wdApp := ComObjCreate("Word.Application") ;create a word app
wdApp.Visible := true
oConnect := ComObjConnect(wdApp,"wd_") ;connect to events
wdApp.Documents.Add() ;add a new document


wd_NewDocument(Doc,App) { ;when creating a new document, this triggers
    MsgBox, % Doc.Name                          ; Show the name of the new document
    App.Selection.TypeText("Hello world")       ; Type text at the current selection
}

wd_Close(Doc,App) ;<------------  Here is the problem, I've tried wd_Close,wd_Quit and wd_Exit with no success
    MsgBox, % App.Name ; Show the name of the application
    ComObjConnect(App) ; Disconnect from App events
}

Stavencross

Posts: 90
Joined: 24 May 2016, 16:42

Re: Word COM on Close event capture  Topic is solved

26 Mar 2019, 11:27

I was able to take part of the replies to make the following:

Code: Select all

#Persistent
wdApp := ComObjCreate("Word.Application") ;create a word app
wdApp.Visible := true
oConnect := ComObjConnect(wdApp,"wd_") ;connect to events
wdApp.Documents.Add() ;add a new document


wd_NewDocument(Doc,App) { ;when creating a new document, this triggers
    MsgBox, % Doc.Name                          ; Show the name of the new document
    App.Selection.TypeText("Hello world")       ; Type text at the current selection
}

wd_Quit(App) 
{ 
	MsgBox, % "Yes it's done"    
}

Klarion

Posts: 176
Joined: 26 Mar 2019, 10:02

Re: Word COM on Close event capture

26 Mar 2019, 13:09

1. beg a question
2. get an answer code from someone else
3. check its own comment as an answer
4. conveniently not using the basic word ‘thanks

Brilliant !!!

User avatar

jeeswg

Posts: 6902
Joined: 19 Dec 2016, 01:58
Location: UK

Re: Word COM on Close event capture

26 Mar 2019, 14:51

I thought it was a good contribution. Thanks Klarion!

I can tell you that not every response I’ve experienced or witnessed was fair. Sometimes you even get too much credit, someone marks yours as the answer, when you preferred the other one. And sometimes no response is better than a bad response. But on average responses are pretty good.

I’d respond to you here, but I don’t want to receive notifications from that thread. Cheers.
Issues with registering, Post your username here… — Page 33 — AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=2&t=5008&p=269624#p269624

Stavencross

Posts: 90
Joined: 24 May 2016, 16:42

Re: Word COM on Close event capture

27 Mar 2019, 08:18

Klarion wrote: ↑

26 Mar 2019, 13:09


1. beg a question
2. get an answer code from someone else
3. check its own comment as an answer
4. conveniently not using the basic word ‘thanks

Brilliant !!!

Apologies, I had written a response with a thank you in it and forgot to click submit on my way to a meeting.

Thank you very much for your assistance, there were a couple things I had to add to your code to make it work correctly, including the #Persistent tag, hence why I posted mine and chose it as the answer. I appreciate your assistance though. Thank you again!


Return to “Ask for Help (v1)”

Понравилась статья? Поделить с друзьями:
  • Word application new document
  • Word application is running
  • Word application in net
  • Word application format text
  • Word application for windows