Word Macro: Saving All Files

This Word VBA macro saves all documents.

Macro Example

Sub SaveAllDocuments() 

  Dim doc As Document

  On Error Resume Next

 For Each doc In Documents
    doc.Save
 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

On Error Resume Next

Sub...

  Dim doc As Document

  On Error Resume Next

A run-time error will occur at the 8th line (doc.Save), if there is a file has not saved.
So, the 5th line aims to ignore this run-time error.

Starts Looping

Sub...

  Dim doc As Document

  On Error Resume Next

 For Each doc In Documents

The 7th 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

Saves Each Document

Sub...

  Dim doc As Document

  On Error Resume Next

 For Each doc In Documents
    doc.Save

The 8th line saves the document by the Document.Save method.

obj-Word-Document-Save

Loops Back

Sub...

  Dim doc As Document

  On Error Resume Next

 For Each doc In Documents
    doc.Save
 Next doc

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

After every document is saved, this macro ends.

Sub SaveAllDocuments() 

  Dim doc As Document

  On Error Resume Next

 For Each doc In Documents
    doc.Save
 Next doc

End Sub

Properties

http://www.relief.jp/itnote/archives/word-vba-save-all-files.php

Apply To

  • Word 2013
  • Word 2010
  • Word 2007