开发者

Trigger MS Word macro after save event

开发者 https://www.devze.com 2023-01-14 03: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.

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 开发者_如何学JAVAto 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?


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!


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消