Monday, August 10, 2015

A MS Word Macro for Auto Footer Generation

Here is a Microsoft Word macro that I worked up for a situation where I was trying to print a large number of .rtf files that didn't have any footer, but I wanted a footer that contained the filename, the print date and time, and the current page (of the total pages). It should work for printing other types of files, such as .doc, .docx, .txt, or possibly whatever you can open with word.

In my case, I didn't want to save the footer, so I wrote a second macro that calls the first one, to print the file and exit without saving the file.


Sub GenerateFooterAndInfo()
'
'
    If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
        ActiveWindow.Panes(2).Close
    End If
    If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
        ActivePane.View.Type = wdOutlineView Then
        ActiveWindow.ActivePane.View.Type = wdPrintView
    End If
    ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter
 
    'add filename to left side of footer
    Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
        "FILENAME  ", PreserveFormatting:=True
    Selection.TypeText Text:=vbTab
 
    'add date to center of footer
    Selection.InsertDateTime DateTimeFormat:="M/d/yyyy h:mm:ss am/pm", _
        InsertAsField:=True, DateLanguage:=wdEnglishUS, CalendarType:= _
        wdCalendarWestern, InsertAsFullWidth:=False
    Selection.TypeText Text:=vbTab
 
    'add page of pagecount to right side of footer
    Selection.TypeText Text:="Page "
    Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
        "PAGE  ", PreserveFormatting:=True
    Selection.TypeText Text:=" of "
    Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
        "NUMPAGES  ", PreserveFormatting:=True
    ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument

End Sub



And here is the second macro that avoids saving the changes:




Sub CreateTempFooterThenPrintAndExit()
'
'
    GenerateFooterAndInfo
 
    ActiveDocument.PrintOut
 
    'close document without saving autogenerated footer
    ActiveWindow.Close (False)
    Application.Quit
 
End Sub


These macros make it easy to open a file and immediately print it, without changing the file, and yet having the information about the file easily at hand. These could be easily modified to print the path to the filename, etc. for either headers or footers in Word documents.

Hope this helps someone out there.