我在关闭Word文档的事件处理函数中遇到了一些奇怪的行为。我在我的Outlook模块中使用Word的DocumentBeforeClose事件处理程序。在处理程序中,我会提示用户是否要完成文档、放弃文档或继续编辑。
如果我使用带有vbYesNoCancel按钮的MsgBox函数,则每次关闭Word文档时都会触发事件处理程序。这符合预期。
如果我使用自定义用户表单来代替,则事件处理程序只在第一次关闭Word文档时触发。如果用户选择“继续编辑”,那么下次关闭文档时,事件处理程序就不会触发了。
我不明白为什么这两种情况会导致不同的行为?为什么使用自定义用户表单会取消事件处理程序?
事件处理程序类(不起作用的版本)
Option Explicit
Private WithEvents mWordApp As word.Application
Private Sub mWordApp_DocumentBeforeClose(ByVal Doc As document, Cancel As Boolean)
Dim msgBoxResponse As String
'This code brings Outlook back to the active window so the user can response to the form
AppActivate Application.ActiveExplorer.Caption
SendKeys "%"
Set finaliseUserForm = New UserFormFinaliseRFI
finaliseUserForm.show
msgBoxResponse = finaliseUserForm.response
Unload finaliseUserForm
Set finaliseUserForm = Nothing
'msgBoxResponse = MsgBox("Do you want to finalise the document?", vbYesNoCancel)
If msgBoxResponse = "Finalise" Then
'If msgBoxResponse = vbYes Then
Set mWordApp = Nothing
Else
Cancel = True
AppActivate "test.docx"
End If
End Sub
Public Sub StartEvents()
Set mWordApp = CreateObject("Word.Application")
End Sub
Public Sub OpenWordDocument(filePath As String)
mWordApp.Documents.Open filePath
mWordApp.Visible = True
End Sub
事件处理程序类(工作版本)
Option Explicit
Private WithEvents mWordApp As word.Application
Private Sub mWordApp_DocumentBeforeClose(ByVal Doc As document, Cancel As Boolean)
Dim msgBoxResponse As String
'This code brings Outlook back to the active window so the user can response to the form
AppActivate Application.ActiveExplorer.Caption
SendKeys "%"
'Set finaliseUserForm = New UserFormFinaliseRFI
'finaliseUserForm.show
'msgBoxResponse = finaliseUserForm.response
'Unload finaliseUserForm
'Set finaliseUserForm = Nothing
msgBoxResponse = MsgBox("Do you want to finalise the document?", vbYesNoCancel)
'If msgBoxResponse = "Finalise" Then
If msgBoxResponse = vbYes Then
Set mWordApp = Nothing
Else
Cancel = True
AppActivate "test.docx"
End If
End Sub
Public Sub StartEvents()
Set mWordApp = CreateObject("Word.Application")
End Sub
Public Sub OpenWordDocument(filePath As String)
mWordApp.Documents.Open filePath
mWordApp.Visible = True
End Sub
测试模块子
Option Explicit
Private mEvents As WordEventsHelper
Public Sub testEvents()
Set mEvents = New WordEventsHelper
mEvents.StartEvents
mEvents.OpenWordDocument "\(mypath)\test.docx"
AppActivate "test.docx"
End Sub
用户表单代码
Private mResponse As String
Public Property Get response() As String
response = mResponse
End Property
Private Sub CommandButtonFinalise_Click()
mResponse = "Finalise"
Me.Hide
End Sub
Private Sub CommandButtonDiscard_Click()
mResponse = "Discard"
Me.Hide
End Sub
Private Sub CommandButtonContinueEditing_Click()
mResponse = "Continue Editing"
Me.Hide
End Sub
Unload
方法而不是Hide
。 - Eugene Astafiev