Word Macro: Closing All Documents

This Word VBA macro closes all documents.

Macro Example

Sub CloseAllDocuments() 

  Dim doc As Document

 For Each doc In Documents
    doc.Close
 Next doc

End Sub

Description

Variable Declaration

Sub...

  Dim doc As Document

The 3rd line declares an object variable named doc that will refer to the Document object.

The Document object represents a single Word document.

obj-Word-Document

Starts Looping

Sub...

  Dim doc As Document

 For Each doc In Documents

The 5th line starts to loop through all the elements (Document) of a collection (Documents).

[Application.]Documents

The [Application.]Documents property returns the Documents collection object.

obj-Word-Application-Documents

The Documents property is a member of the Word.Global class, so we can omit the Application property.

obj-Word-Documents

The Documents is a collection of all the Document objects those are currently open in Word.

obj-Word-Documents

Closes Each Document

Sub...

  Dim doc As Document

 For Each doc In Documents
    doc.Close

The 6th line closes the document by the Document.Close method.

Loops Back

Sub...

  Dim doc As Document

 For Each doc In Documents
    doc.Close
 Next doc

The 7th line loops back to get the next document.

After every document is closed, this macro ends.


Properties

http://www.relief.jp/itnote/archives/word-macro-close-all-documents.php

Apply To

  • Word 2013
  • Word 2010
  • Word 2007