【问题标题】:Word VBA - DocumentBeforeSave event?Word VBA - DocumentBeforeSave 事件?
【发布时间】:2015-06-25 15:44:33
【问题描述】:

我正在使用以下 VBA 代码在保存 Word 文档时显示一个消息框,

Public WithEvents appWord as Word.Application 

Private Sub appWord_DocumentBeforeSave _ 
 (ByVal Doc As Document, _ 
 SaveAsUI As Boolean, _ 
 Cancel As Boolean) 

 Dim intResponse As Integer 

 intResponse = MsgBox("Do you really want to " _ 
 & "save the document?", _ 
 vbYesNo) 

 If intResponse = vbNo Then Cancel = True 
End Sub

这段代码是在一个类中编写的。但这不起作用。保存时没有任何反应。这里有什么问题?

【问题讨论】:

    标签: vba ms-word savefiledialog before-save


    【解决方案1】:

    我让它工作了。感谢AnalystCave.com 的帮助。这就是我所做的:

    我创建了一个名为 EventClassModule 的新类并复制了以下代码,

    Public WithEvents App As Word.Application
    
    Private Sub App_DocumentBeforeSave _
     (ByVal Doc As Document, _
     SaveAsUI As Boolean, _
     Cancel As Boolean)
    
     Dim intResponse As Integer
    
     intResponse = MsgBox("Do you really want to " _
     & "save the document?", _
     vbYesNo)
    
     If intResponse = vbNo Then Cancel = True
    End Sub
    

    然后创建一个名为mdlEventConnect的模块并复制以下代码,

    Dim X As New EventClassModule
    
    Sub Register_Event_Handler()
     Set X.App = Word.Application
    End Sub
    

    之后在ThisDocument上复制以下代码,

    Private Sub Document_New()
        Register_Event_Handler
    End Sub
    
    Private Sub Document_Open()
        Register_Event_Handler
    End Sub
    

    保存文档并重新打开它。现在,当我尝试保存文档时,它完美地执行了 DocumentBeforeSave 事件。

    【讨论】:

      【解决方案2】:

      将它放在 Word 中 VBA 项目的 ThisDocument 部分,而不是放在 Class 中,因为它在那里不起作用。

      这是一个例子: https://msdn.microsoft.com/en-us/library/office/ff838299.aspx

      【讨论】:

        【解决方案3】:

        对于 Word 2016,我发现有必要进行更改

        Set X.App = Word.Application
        

        应该是

        Set X.appWord = Word.Application
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-10
          • 1970-01-01
          • 2018-05-28
          • 2012-04-13
          相关资源
          最近更新 更多