保存后触发MS Word宏

7

我的MS Word 2007模板有一个页脚,其中包含文件名。用户将打开模板并执行“另存为…”以制作他们的文档。

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

是否有一个AfterSaveEvent或其他可以用作挂钩来启动我的VBA脚本进行更新的方法?

还是有更简单的方法吗?

3个回答

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

每当用户选择“文件另存为”时,它就会被触发。
希望这有所帮助!

谢谢你的回答。我的IT同事正在进行一些测试……如果它奏效的话,我会将其标记为已接受。 - blokeley
@blokeley 请在下面留言并发布结果。祝你好运! - Dr. belisarius
太棒了,第一次就成功了。我会在下面发布完整的解决方案供其他人参考。 - blokeley

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

1
我们知道 Microsoft Word 没有提供 Aftersave 事件。但是 Word 允许我们使用 BeforeSave 事件。我已经实现了这个解决方案,它运行良好。
首先,我们需要在 Word 的 BeforeSave 事件中实现 Application.onTime 方法,如下所示。
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 循环之后实现您的代码。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接