Article ID: 182429
Article Last Modified on 11/23/2006
if { page }={ numpages } "{ filename \p }"
so that the field looks like this:
{ if { page } = { numpages } "{ filename \p }" }
NOTE: The \p switch causes the entire path to the file name to be
included.
Sub PutFileNameOnLastPage()
' Are any documents open?
If Documents.Count = 0 Then Exit Sub
' Go to footer of document in the last section
' of the document.
Selection.EndKey Unit:=wdStory
If ActiveWindow.ActivePane.View.Type = wdNormalView Or _
ActiveWindow.ActivePane.View.Type = wdOutlineView Or _
ActiveWindow.ActivePane.View.Type = wdMasterView Then
ActiveWindow.ActivePane.View.Type = wdPageView
End If
ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter
' If the document already contains a filename, exit this routine.
For Each ao In Selection.HeaderFooter.Range.Fields
If ao.Type = wdFieldFileName Then
MsgBox "This document already contains a filename."
Exit Sub
End If
Next
' Add the Filename field.
ActiveWindow.View.ShowFieldCodes = True
With Selection
.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
"IF ", PreserveFormatting:=True
.MoveRight Unit:=wdCharacter, Count:=5
.Fields.Add Range:=Selection.Range, Type:=wdFieldPage
.TypeText Text:=" = "
.Fields.Add Range:=Selection.Range, Type:=wdFieldNumPages
.TypeText Text:=" "
.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
"FILENAME \p "
Selection.HeaderFooter.Range.Fields.Update
End With
' Turn field codes off.
ActiveWindow.View.ShowFieldCodes = False
' Close the footer and return to document.
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
End Sub
The If field determines whether the current page equals the number of pages
in the document. This field is present in the header or footer on every
page in the document. However, the file name will be printed only on the
final page of the document. These steps can be used with any field (that
is, you can substitute another field code for the file name if you want
different results to print, such as the date).
181058 OFF98: How to Run Sample Code from Knowledge Base Articles
163435 VBA: Programming Resources for Visual Basic for Applications
Additional query words: wordcon vb vba vbe
Keywords: kbcode kbdtacode kbinfo kbmacroexample kbprogramming KB182429