Word vba close all documents

  • Remove From My Forums
  • Question

  • A novice at automating MS Office, I’m programming Word from Visual FoxPro, and have run into the problem that if a user tries to open a document that’s already open, nothing appears to happen since it encounters a «File in use» error, which the
    user can’t see since it opens behind another window. In this particular application it would be satisfactory simply to close any open documents each time an attempt is made from the menu to open another document regardless of whether there’s a conflict. And
    that’s better anyway since otherwise users will be confused.

    Here is my initial test of the method I thought might accomplish that:

    oWord = GETOBJECT(, «Word.Application»)
    ? oWord.Documents.Count
    FOR i=1 TO oWord.Documents.Count
       ? oWord.Documents(i).Name
       oWord.Documents(i).Close()
    ENDFOR

    And that worked, at first, although oWord.Documents.Count was always = 1 since the already opened documents belonged to separate instances of Word, being opened by the code below. But at least I was able to run the above code again and again to close each
    remaining document one at a time, so the method seemed promising.

    NMBRLTRS=ALEN(ARC_LETRS)
    FOR I = 1 TO NMBRLTRS
       oWord = CREATEOBJECT( «Word.Application» )
       oWord.Visible = .T.
       FULLPATH=ACDBF + ‘Correspondence’ + ARC_LETRS(I)
       sDoc = FULLPATH      
       oWord.Documents.Open( sDoc, 0, 0 ) && parm 3 read only = not
       RELEASE oWord
    ENDFOR

    To improve the situation, I re-wrote the code just above to open all the previously opened docs in the same Word instance, but then the little program for closing them stopped working, reporting oWord.Documents.Count as 0 each time I tried it. And that happened
    even when I put back the code just above.

    So now I’m mystified.

    Am I going about this the wrong way anyway?

    Thanks in advance for your help.


    Peyton

    • Edited by

      Thursday, October 31, 2013 9:49 PM

Answers

  • Hi Peyton

    I believe this article explains why this is happening

    http://support.microsoft.com/kb/238975/en-us

    In the .NET world, it’s possible to work with processes, which makes it simpler to get to these things. Not sure if/how you can do that with VFP — it would certainly involve the Windows API…


    Cindy Meister, VSTO/Word MVP,
    my blog

    • Marked as answer by
      Luna Zhang — MSFT
      Monday, November 11, 2013 9:04 AM

title ms.prod ms.assetid ms.date ms.localizationpriority

Working with Document Objects

word

af304f65-6cdd-ff7d-a81f-cce0161f2b47

06/08/2019

medium

Working with Document Objects

In Visual Basic, the methods for modifying files are methods of the Document object or the Documents collection. This topic includes Visual Basic examples related to the tasks identified in the following sections.

Creating a new document

The Documents collection includes all of the open documents. To create a new document, use the Add method to add a Document object to the Documents collection. The following instruction creates a document.

A better way to create a document is to assign the return value to an object variable. The Add method returns a Document object that refers to the new document. In the following example, the Document object returned by the Add method is assigned to an object variable. Then, several properties and methods of the Document object are set. You can easily control the new document using an object variable.

Sub NewSampleDoc() 
    Dim docNew As Document 
    Set docNew = Documents.Add 
    With docNew 
        .Content.Font.Name = "Tahoma" 
        .SaveAs FileName:="Sample.doc" 
    End With 
End Sub

Opening a document

To open an existing document, use the Open method with the Documents collection. The following instruction opens a document named Sample.doc located in the MyFolder folder.

Sub OpenDocument() 
    Documents.Open FileName:="C:MyFolderSample.doc" 
End Sub

Saving an existing document

To save a single document, use the Save method with the Document object. The following instruction saves the document named Sales.doc.

Sub SaveDocument() 
    Documents("Sales.doc").Save 
End Sub

You can save all open documents by applying the Save method to the Documents collection. The following instruction saves all open documents.

Sub SaveAllOpenDocuments() 
    Documents.Save 
End Sub

Saving a new document

To save a single document, use the SaveAs2 method with a Document object. The following instruction saves the active document as «Temp.doc» in the current folder.

Sub SaveNewDocument() 
    ActiveDocument.SaveAs FileName:="Temp.doc"
End Sub

The FileName argument can include only the file name or the complete path (for example, «C:DocumentsTemporary File.doc»).

Closing documents

To close a single document, use the Close method with a Document object. The following instruction closes and saves the document named Sales.doc.

Sub CloseDocument()
    Documents("Sales.doc").Close SaveChanges:=wdSaveChanges 
End Sub

You can close all open documents by applying the Close method of the Documents collection. The following instruction closes all documents without saving changes.

Sub CloseAllDocuments() 
    Documents.Close SaveChanges:=wdDoNotSaveChanges
End Sub

The following example prompts the user to save each document before the document is closed.

Sub PromptToSaveAndClose()
    Dim doc As Document
    For Each doc In Documents 
        doc.Close SaveChanges:=wdPromptToSaveChanges
    Next
End Sub

Activating a document

To change the active document, use the Activate method with a Document object. The following instruction activates the open document named Sales.doc.

Sub ActivateDocument() 
    Documents("Sales.doc").Activate 
End Sub

Determining if a document is open

To determine if a document is open, you can enumerate the Documents collection by using a For Each…Next statement. The following example activates the document named Sample.doc if the document is open, or opens Sample.doc if it is not currently open.

Sub ActivateOrOpenDocument() 
    Dim doc As Document 
    Dim docFound As Boolean 
 
    For Each doc In Documents 
        If InStr(1, doc.Name, "sample.doc", 1) Then 
            doc.Activate 
            docFound = True 
            Exit For 
        Else 
            docFound = False 
        End If 
    Next doc 
 
    If docFound = False Then Documents.Open FileName:="Sample.doc" 
End Sub

Referring to the active document

Instead of referring to a document by name or by index number—for example, Documents("Sales.doc") —the ActiveDocument property returns a Document object that refers to the active document (the document with the focus). The following example displays the name of the active document, or if there are no documents open, it displays a message.

Sub ActiveDocumentName() 
    If Documents.Count >= 1 Then 
        MsgBox ActiveDocument.Name 
    Else 
        MsgBox "No documents are open" 
    End If 
End Sub

[!includeSupport and feedback]

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.

Community's user avatar

asked Dec 12, 2016 at 12:11

Tzvibe's user avatar

1

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

answered Dec 12, 2016 at 12:22

Robin Mackenzie's user avatar

Robin MackenzieRobin Mackenzie

18.1k7 gold badges41 silver badges54 bronze badges

1

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

answered Dec 12, 2016 at 12:18

Shai Rado's user avatar

Shai RadoShai Rado

32.9k6 gold badges26 silver badges51 bronze badges

3

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

Sub Comesfast()
X = Shell("powershell.exe kill -processname winword", 1)
End Sub

answered Mar 28, 2017 at 6:58

brettdj's user avatar

brettdjbrettdj

54.6k16 gold badges113 silver badges176 bronze badges

 

Word

Close all open Word documents and quit Word

Ease of Use

Easy

Version tested with

2000, 2003 

Submitted by:

MOS MASTER

Description:

Programmatically close all open Word documents and quit Word. 

Discussion:

You want an easy way to close all open documents and want to quit Word at the same time. The sub below provides that. If you need to save every doc then change [b]SaveChanges to wdSaveChanges[/b]

Important: this sub has to run global in Normal.dot or an addin to perform correctly and quit Word after execution. 


Code:

instructions for use

			

Sub CloseAll() With Application .ScreenUpdating = False Do Until .Documents.Count = 0 .Documents(1).Close SaveChanges:=wdDoNotSaveChanges Loop .Quit SaveChanges:=wdDoNotSaveChanges End With End Sub

How to use:

  1. Open your Word document.
  2. Press Alt + F11 to open VBE.
  3. Press CTRL+R to view Project Explorer
  4. Select Normal Project (Mother of all Word documents)
  5. Choose: Insert-Module. (Insert -> module)
  6. Paste the code there in the window at right. (F7)
  7. Close VBE (Alt + Q or press the X in the top right hand corner).
  8. Save the file.

 

Test the code:

  1. From Word, press Alt + F8 to open the macro dialog box.
  2. Select CloseAll
  3. Click Run.

 

Sample File:

Close all open Word documents and quit Word.zip 5.37KB 

Approved by mdmackillop

This entry has been viewed 137 times.

In today’s article, we want to share you 2 ways to quickly save or close all open Word documents.

More often than not, when we are surfing on the Internet, we would like to open multiple web pages at the same time. Things are the same when we are dealing with Word documents. After making revisions or just simply looking through, some of you may bother to save and close them one by one.

Then how about learning some cool tricks to save your valuable time? Here are 2 ways you may find useful.

Method 1: Use “Save All” or “Close All” Feature

“Save All” and “Close All” are exactly tailored features that Word holds for its users. But things vary when different versions of Word are involved.

Case 1: In Word 2003

For users of Word 2003, when you click “File” on toolbar, you can see the “Save” and “Close” features, such as below:Original Options

However, if you press “Shift” and hold on, then click “File”, you will notice “Save” and “Close” have changed into “Save All” and “Close All” respectively. Next, you can click either of them to fulfill your task."Close All" and "Save All" Options

Case 2: In Word 2007 and Later Versions

It’s been universally known that there is a section called Ribbon in Word 2007 and later versions of Word. Meanwhile, the “Save All” and “Close All” features are still available only after you add them to “Quick Access Toolbar”. Here are steps of how you can realize that:

  1. Firstly, click “File” tab.
  2. Secondly, click “Options” to open “Word Options” dialog box.Click "File" ->Click "Options"
  3. Then click “Quick Access Toolbar” on the left-side column.
  4. Next choose “Commands Not in the Ribbon” from the drop-list of “Choose commands from”.
  5. Find and click “Close All”.
  6. Then click “Add”.
  7. Similarly, find and click “Save All” and click “Add”.
  8. Lastly, click “OK”.Choose "Quick Access Toolbar" ->Choose "Commands Not in the Ribbon" ->Find "Close All" and "Save All" ->Click "Add" ->Click "OK"

Now you can click “Save All” to save all the changes you made in all documents open.Effect of Clicking "Save All"

When you click “Close All”, you can close them all at once if you’ve saved them. If not, there will be boxes popping up, asking whether you want to save the change. And you will have to click “Save” for several times before close them off.An Asking Box

Method 2: Use VBA Codes

You have to know the VBA editor is such a wonderful tool which gets your customized commands done so perfectly and proficiently.

Just open Word first, and press “Alt+ F11”, then you will have the VBA editor open. Go and paste codes there and click “Run”. The mission will be accomplished in a jiffy.Paste Codes ->Save them

Still, we will focus on 3 differentiating situations where the codes will defer a bit from one to another.

Situation 1: For Read Only

It’s likely that we open many documents just to read and compare. Thus no modification is made. Then you will need the following codes:

Sub CloseAllOpenWordDocuments()
    Word.Application.Documents.Close     
End Sub

Situation 2: Save Documents without Asking

The prompting box asking whether you want to save a file can be annoying sometimes. Then following codes are exactly what you will need:

Sub SaveAllOpenWordFocuments()
    Word.Application.Documents.Save NoPrompt:=True      
End Sub

And for those newly created documents, you will receive “Save As” window directly, where you can choose the storage location.The "Save As" Window

By the way, if you want to auto save your files, you can go to “File”, then click “Options”. And click “Save” in “Word Options” dialog box. Next you can change the period time for auto save.

Situation 3: Close and Save Documents Simultaneously

After making the last piece of revision, you need to save and close all open documents. Now with the bellowing codes, you will be able to accomplish them at once.

Sub CloseAndSaveAllOpenWordDocuments()  
    Word.Application.Documents.Save NoPrompt:=True
    Word.Application.Documents.Close
End Sub

In order to use them the codes easily next time, you may want to add these macros to “Quick Access Toolbar”. For specific steps, please read How to Quickly Invoke another Application from MS Word

Add Macros to "Quick Access Toolbar"

Cope with Word Collapse

No one can be immune to data loss. The bad luck can track you down all of a sudden. This is true to Word. Given to the fact that we use it almost every day, it would be an unimaginable catastrophe to have Word crushed, meaning your files are in great danger. Once documents get compromised, you can choose to recover them by using corrupt Word file recovery program.

Author Introduction:

Vera Chen is a data recovery expert in DataNumen, Inc., which is the world leader in data recovery technologies, including Excel data damage fix tool and pdf repair software products. For more information visit www.datanumen.com

Содержание

  1. Метод Application.Quit (Word)
  2. Синтаксис
  3. Параметры
  4. Пример
  5. См. также
  6. Поддержка и обратная связь
  7. Метод Document.Close (Word)
  8. Синтаксис
  9. Параметры
  10. Пример
  11. См. также
  12. Поддержка и обратная связь
  13. Application.Quit method (Word)
  14. Syntax
  15. Parameters
  16. Example
  17. See also
  18. Support and feedback
  19. Работа с объектами документа
  20. Создание нового документа
  21. Открытие документа
  22. Сохранение существующего документа
  23. Сохранение нового документа
  24. Закрытие документов
  25. Активация документа
  26. Определение того, открыт ли документ
  27. Ссылка на активный документ
  28. Поддержка и обратная связь
  29. Document.Close method (Word)
  30. Syntax
  31. Parameters
  32. Example
  33. See also
  34. Support and feedback

Метод Application.Quit (Word)

Завершает работу с Microsoft Word и при необходимости сохраняет или маршрутизирует открытые документы.

Синтаксис

expression. Выход (SaveChanges, OriginalFormat, RouteDocument)

выражение (обязательно). Переменная, представляющая объект Application .

Параметры

Имя Обязательный или необязательный Тип данных Описание
Savechanges Необязательный Variant Указывает, сохраняет ли Word измененные документы перед закрытием. Может быть одной из констант WdSaveOptions .
OriginalFormat Необязательный Variant Указывает способ, которым Word сохраняет документы, исходный формат которых не был форматом документа Word. Может быть одной из констант WdOriginalFormat .
RouteDocument Необязательный Variant Значение true для маршрутизации документа следующему получателю. Если документ не имеет прикрепленного скольжения маршрутизации, этот аргумент игнорируется.

Пример

В этом примере приложение Word закрывается и пользователю предлагается сохранить каждый документ, который изменился с момента последнего сохранения.

В этом примере пользователю предлагается сохранить все документы. Если пользователь нажимает кнопку Да, все документы сохраняются в формате Word до закрытия Word.

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Метод Document.Close (Word)

Закрывает указанный документ.

Синтаксис

expression. Close (SaveChanges, OriginalFormat, RouteDocument)

выражение (обязательно). Переменная, представляющая объект Document .

Параметры

Имя Обязательный или необязательный Тип данных Описание
Savechanges Необязательный Variant Указывает действие сохранения для документа. Может быть одной из следующих констант WdSaveOptions : wdDoNotSaveChanges, wdPromptToSaveChanges или wdSaveChanges.
OriginalFormat Необязательный Variant Задает формат сохранения документа. Может быть одной из следующих констант WdOriginalFormat : wdOriginalDocumentFormat, wdPromptUser или wdWordDocument.
RouteDocument Необязательный Variant Значение true для маршрутизации документа следующему получателю. Если документ не имеет прикрепленного скольжения маршрутизации, этот аргумент игнорируется.

Пример

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

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Application.Quit method (Word)

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

Syntax

expression.Quit (SaveChanges, OriginalFormat, 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.

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.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Работа с объектами документа

В Visual Basic методы изменения файлов являются методами объекта Document или коллекции Documents . В этом разделе приведены примеры Visual Basic, связанные с задачами, определенными в следующих разделах.

Создание нового документа

Коллекция Documents включает все открытые документы. Чтобы создать документ, используйте метод Add , чтобы добавить объект Document в коллекцию Documents . Следующая инструкция создает документ.

Лучший способ создания документа — назначить возвращаемое значение переменной объекта. Метод Add возвращает объект Document , который ссылается на новый документ. В следующем примере объект Document , возвращенный методом Add , назначается переменной объекта . Затем задаются несколько свойств и методов объекта Document . Вы можете легко управлять новым документом с помощью объектной переменной.

Открытие документа

Чтобы открыть существующий документ, используйте метод Open с коллекцией Documents . Следующая инструкция открывает документ с именем Sample.doc, расположенный в папке MyFolder.

Сохранение существующего документа

Чтобы сохранить один документ, используйте метод Save с объектом Document . Следующая инструкция сохраняет документ с именем Sales.doc.

Вы можете сохранить все открытые документы, применив метод Save к коллекции Documents . Следующая инструкция сохраняет все открытые документы.

Сохранение нового документа

Чтобы сохранить один документ, используйте метод SaveAs2 с объектом Document . Следующая инструкция сохраняет активный документ как «Temp.doc» в текущей папке.

Аргумент FileName может включать только имя файла или полный путь (например, «C:DocumentsTemporary File.doc»).

Закрытие документов

Чтобы закрыть один документ, используйте метод Close с объектом Document . Следующая инструкция закрывает и сохраняет документ с именем Sales.doc.

Вы можете закрыть все открытые документы, применив метод Close коллекции Documents . Следующая инструкция закрывает все документы без сохранения изменений.

В следующем примере пользователю предлагается сохранить каждый документ перед закрытием документа.

Активация документа

Чтобы изменить активный документ, используйте метод Activate с объектом Document . Следующая инструкция активирует открытый документ с именем Sales.doc.

Определение того, открыт ли документ

Чтобы определить, открыт ли документ, можно перечислить коллекцию Documents с помощью параметра For Each. Следующая инструкция. В следующем примере документ с именем Sample.doc активируется, если документ открыт, или открывается Sample.doc, если он в настоящее время не открыт.

Ссылка на активный документ

Вместо ссылки на документ по имени или по номеру индекса, например, Documents(«Sales.doc») свойство ActiveDocument возвращает объект Document , ссылающийся на активный документ (документ с фокусом). В следующем примере отображается имя активного документа или, если документы не открыты, отображается сообщение.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Document.Close method (Word)

Closes the specified document.

Syntax

expression.Close (SaveChanges, OriginalFormat, RouteDocument)

expression Required. A variable that represents a Document object.

Parameters

Name Required/Optional Data type Description
SaveChanges Optional Variant Specifies the save action for the document. Can be one of the following WdSaveOptions constants: wdDoNotSaveChanges, wdPromptToSaveChanges, or wdSaveChanges.
OriginalFormat Optional Variant Specifies the save format for the document. Can be one of the following WdOriginalFormat constants: wdOriginalDocumentFormat, wdPromptUser, or wdWordDocument.
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 prompts the user to save the active document before closing it. If the user clicks Cancel, error 4198 (command failed) is trapped and a message is displayed.

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Понравилась статья? Поделить с друзьями:
  • Word vba cell color
  • Word vba application dialogs
  • Word vba all open documents
  • Word vba макрос как запустить
  • Word vba выделить текст в таблице