Bra Utbildning AB

 

<-- Back
VBA & Object models
Work with text
Bookmarks
Ranges
Fields
Form fields
Autotext
Doc var & Doc Prop
Built-in commands
Built-in dialogs
Automation
External databases

Work with fields

Example 1: Update fields in the document
ActiveDocument.Fields.Update

Example 2: A more complete update of fields
Dim oRng As Range

For Each oRng In ActiveDocument.StoryRanges
   If Not oRng.StoryType = wdCommentsStory Then
      oRng.Fields.Update
   End If
Next

Example 3: A complete update of fields in the document
Dim oRng As Range
Dim oField As Field

For Each oRng In ActiveDocument.StoryRanges
   oRng.Fields.Update
   If Not oRng.StoryType = wdMainTextStory Then
      While Not oRng.NextStoryRange Is Nothing
         Set oRng = oRng.NextStoryRange
         If Not oRng.StoryType = wdCommentsStory Then
            For Each oField In oRng.Fields
               oField.Update
            Next
         End If
      Wend
   End If
Next



Insert a field at a predefined range in the document (oRng). After insertion the field is converted to plain text. This can be done differently but it shows how to go about to add a field. 

Example: Date with a specified format is inserted in the document as a field, then converted into plain text.

With ActiveDocument
   .Styles(wdStyleNormal).LanguageID = wdEnglishUK ' or US

   .Fields.Add Range:=oRng, _
      Type:=wdFieldCreateDate, _
      Text:="\@ ""MMM d, yyyy"""

   'can also be done this way around
   ' .Fields.Add Range:=oRng, _
   ' Type:=wdFieldEmpty, _
   ' Text:="CREATEDATE \@ ""MMM d, yyyy""", _
   ' Preserveformatting:=True

  .Fields.Unlink
End With

Field codes in the document

The codes can be added manually or with code. This feature is often asked for and used in the header in many documents. It will display both the actual page's number and the total number of pages like  1(17). The numbering will only be displayed in documents longer than one page.
{ IF { NumPages } > 1 "{ Page } ({ NumPages })" }