【问题标题】:Trigger MS Word macro after save event保存事件后触发 MS Word 宏
【发布时间】:2010-09-03 14:16:57
【问题描述】:

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

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

是否有 AfterSaveEvent 或可以用作挂钩来启动执行更新的 VBA 脚本的东西?

或者有更简单的方法吗?

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回答。我的 IT 小伙子正在对其进行一些测试...如果可行,会将其标记为已接受。
    • @bokeley 请对结果发表评论。祝你好运!
    • 太好了,第一次成功。我将在下面为其他人发布完整的解决方案。
    【解决方案2】:

    这基于@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
    

    【讨论】:

      【解决方案3】:

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

      首先我们要在WordBeforeSave事件中实现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循环之后实现你的代码。

      【讨论】: