Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger MS Word macro after save event

Tags:

ms-word

vba

My MS Word 2007 template has a footer with the filename in it. The user is going to open the template and do a "Save As..." to make their document.

I want the filename shown in the footer to update immediately to the new filename.

Is there an AfterSaveEvent or something that I can use as a hook to start my VBA script that does the update?

Or is there a much easier way?

like image 447
blokeley Avatar asked Sep 03 '10 14:09

blokeley


People also ask

How do I make a Word macro run automatically?

To do this, follow these steps: Select the Developer tab, and then select Record Macro in the Code group. In the Record Macro dialog box, type Auto-Exec under Macro name, and then select OK. By default, the macro is saved in the Normal template.

How do I save a macro for future use in Word?

To record a macro, select “Record Macro,” found on the Developer tab. You can give your macro any name that you'd like, as long as there are no spaces in the name. The “Store macro in” dropdown menu gives you the option to save the macro to all future Word documents or only to documents based on your template.

How do you check if a Word file has a macro?

Here's how you can find macros and VBA modules in your document: In Word or Excel, click View > Macro > View Macros. In PowerPoint, click View > Macro.


2 Answers

Just create a macro like this (I believe it works better if included in the Normal.dot)

Sub FileSaveAs()
'
' FileSaveAs Macro
' Saves a copy of the document in a separate file
'
Dialogs(wdDialogFileSaveAs).Show

'returns the name including the .doc extension 
 ChosenFileNameAndExtension = ActiveDocument.Name 'Or use .FullName

' Your code here

End Sub

It will be triggered whenever the user selects "File Save As"

HTH!

like image 154
Dr. belisarius Avatar answered Sep 28 '22 04:09

Dr. belisarius


This worked based on @belisarius' answer:

Sub UpdateAll()
    Dim oStory As Object
    Dim oToc As Object

    'Exit if no document is open
    If Documents.Count = 0 Then Exit Sub
    Application.ScreenUpdating = False

    For Each oStory In ActiveDocument.StoryRanges
        oStory.Fields.Update 'Update fields in all stories
    Next oStory

    For Each oToc In ActiveDocument.TablesOfContents
        oToc.Update 'Update table of contents
    Next oToc

    Application.ScreenUpdating = True
End Sub

Sub FileSaveAs()
'
' FileSaveAs Macro
' Saves a copy of the document in a separate file
'
Dialogs(wdDialogFileSaveAs).Show

UpdateAll


End Sub
like image 20
blokeley Avatar answered Sep 28 '22 04:09

blokeley