简体   繁体   中英

Create/Update footer after SaveAs in Word VBA

I want to generate an automatic footer when I save a new MS Word file, and update the footer if I SaveAs the file.

The code below used to work well with an old Word. With the latest Word it only works if I press F12 on the keyboard. Any help would be greatly appreciated!

Sub FileSaveAs()

    Dialogs(wdDialogFileSaveAs).Show

    Dim i As Long
    Dim ThisPath As String
    Dim pName As String
    Dim TextInFooter As String
    Dim FullName As String

    ThisPath = ActiveDocument.Path
    pName = ActiveDocument.Name
    FullName = ThisPath & "\" & pName
    TextInFooter = "This file was saved in: " & FullName & " on the " & Now

    For i = 1 To ActiveDocument.Sections.Count
        With ActiveDocument.Sections(i)
            .Footers(wdHeaderFooterPrimary).Range.Text = TextInFooter
        End With
    Next
End Sub

As you noticed, the new version triggers the FileSaveAs only on F12. Not sure if this is bug or a feature.

If it is only important that the document shows the information in print or on open - my suggested workaround:

You could avoid the insertion into the footer on save and insert it using fields, the document already has the information you are inserting. You simply need to make it visible. The footer would be then:

This file was saved as { FILENAME \\p } the { SAVEDATE \\@ "dd.MM.yyyy HH:mm:ss"}

Adjust the Date/Time format as needed. You have to force the update of the fields - this is where the auto macros come into it.

Sub AutoOpen()
    ' set fields to update before printing (if saved as and printed while open)
    Options.UpdateFieldsAtPrint = True
    ' Update all current fields in just opened document
    ActiveDocument.Fields.Update
End Sub

Sub AutoClose()
    ' update fields when closing
    ActiveDocument.Fields.Update
End Sub

The only difference would be, that you have the full path including file name and extension there. Additionally, there might be times, when the file is saved but not yet opened/closed/printed and has also not updated the fields.

In theory, you could insert the footer into the document with the AutoOpen macro as well ( activedocument.fields.add ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM