Trigger MS Word macro after save event

南笙酒味 提交于 2019-12-23 09:36:17

问题


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?


回答1:


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!




回答2:


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



回答3:


We know that the Aftersave event isn't available for Microsoft Word. But Word allows us to use BeforeSave event. I have implemented this solution and it works fine.

First we have to implement Application.onTime method in 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 the method called 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 be circulated until the document save process is completed. So you can implement you code after the while loop.



来源:https://stackoverflow.com/questions/3636625/trigger-ms-word-macro-after-save-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!