保存事件后触发MS Word宏

时间:2010-09-03 14:16:57

标签: vba ms-word word-vba

我的MS Word 2007模板有一个包含文件名的页脚。用户打算打开模板并执行“另存为...”来制作文档。

我希望页脚中显示的文件名立即更新为新文件名。

是否有AfterSaveEvent或其他东西可用作启动我的VBA脚本进行更新的钩子?

或者有更简单的方法吗?

3 个答案:

答案 0 :(得分:4)

只需创建一个这样的宏(我相信如果包含在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

只要用户选择“文件另存为”

,它就会被触发

HTH!

答案 1 :(得分:1)

这是基于@belisarius的回答:

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

答案 2 :(得分:0)

我们知道Aftersave事件不适用于Microsoft Word。但Word允许我们使用BeforeSave事件。我已经实现了这个解决方案,它运行正常。

首先,我们必须在Word Application.onTime事件中实现BeforeSave方法,如下所示

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

此方法将在2秒后调用名为AfterSave的方法。

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

在此方法中,while循环将循环,直到文档保存过程完成。所以你可以在while循环之后实现你的代码。

相关问题