Running MS Word macro after saving an event

My MS Word 2007 template has a footer with a file name. The user is about to open the template and do "Save As ..." to make his document.

I want the file name displayed in the footer to be updated immediately to the new file name.

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

Or is there a much simpler way?

+6
vba ms-word word-vba
source share
3 answers

Just create a macro like this (I believe it works better if it is included in 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 fire whenever the user selects "Save file as"

NTN!

+4
source share

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 
+1
source share

We know that the Aftersave event Aftersave not available for Microsoft Word. But Word allows us to use the BeforeSave event. I implemented this solution and it works great.

First, we must implement the Application.onTime method in the Word BeforeSave event as follows

 Private Sub mobjWord_DocumentBeforeSave(ByVal Doc As Word.Document, SaveAsUI As Boolean, Cancel As Boolean) Word.Application.OnTime Now + TimeValue("00:00:02"), "AfterSave" End Sub 

This method will call a method named Aftersave after 2 seconds.

 Public Sub AfterSave() While Word.ActiveDocument.Application.BackgroundSavingStatus <> 0 DoEvents Wend 'Implement your code here End Sub 

In this method, the while loop will propagate until the completion of the document saving process. This way you can implement the code after the while loop.

0
source share

All Articles