Visual Basic for Applications/Word

From Wikiversity
Jump to navigation Jump to search

This lesson introduces Word macros.

Objectives and Skills[edit]

Objectives and skills for Word scripting include:

  • Using Microsoft Word objects

Readings[edit]

  1. Microsoft: Inserting Text in a Document
  2. Microsoft: Document Properties
  3. Microsoft: Built-In Document Properties
  4. Microsoft: Built-In Document Property Constants

Multimedia[edit]

Examples[edit]

'This macro inserts document properties at the end of the active document.

Option Explicit

Sub WordMacro()
    ActiveDocument.Content.InsertParagraphAfter
    ActiveDocument.Content.InsertAfter "Name: " & ActiveDocument.Name
    ActiveDocument.Content.InsertParagraphAfter
    ActiveDocument.Content.InsertAfter "Author: " & ActiveDocument.BuiltInDocumentProperties(WdBuiltInProperty.wdPropertyAuthor)
End Sub

Activities[edit]

In these activities you will create macros which interact with Word documents.

  1. Document Properties
    1. Create a macro that inserts document information (properties) at the bottom of the active document. There could be several valid approaches to this solution, but one method would be to use the Document Range property. The information listed below is available either as a document property directly, or is included in the BuiltInDocumentProperties. Your macro should include Option Explicit. Your inserted information should include the following.
      • Document Name
      • Path
      • Title
      • Subject
      • Author
      • Last Author
      • Creation Date
      • Revision Number
      • Total Editing Time
      • Number of Paragraphs
      • Number of Words
      • Spelling Errors
      • Grammatical Errors
  2. Custom Footer
    1. Insert a custom footer into the active document. The footer should include the document's full path and filename on the left, and the date the file was last saved on the right.
  3. Custom Footer with Fields
    1. Repeat Activity 2 inserting a custom footer into the active document that includes the document's full path and filename and date the file was last saved. Now implement the macro as an AutoOpen macro, and use Word fields to insert the filename and date last saved. Ensure that the macro tests to see if a footer is already in the document, and does nothing if a footer already exists.

See Also[edit]

References[edit]

Nuvola apps edu miscellaneous.svg Type classification: this is a lesson resource.