我希望能够关闭我的 MS Word 2021 文档而不提示保存它,我添加了以下代码:
Sub Document_Close()
ActiveDocument.Saved = True
End Sub
这按预期工作,即如果我更改文档的文本,然后关闭它,则不会出现提示。
我的文档上还有一个 ActiveX 命令按钮。当我单击按钮时,我的 VBA 将前景色设置为红色,如下所示:
Sub CommandButton1_Click()
Me.CommandButton1.ForeColor = vbRed
End Sub
这一切都按预期进行。但是,如果我单击命令按钮(不执行任何其他操作),则关闭文档时始终会出现“保存”提示。更改命令按钮属性似乎会导致 Word 强制显示“保存”提示。
有没有办法改变命令按钮的颜色,并且能够关闭文档而不提示保存?
解决方案是使用Application BeforeClose事件,如下: 创建一个类模块如下:
'
' Class to manage application events.
' Used to close the document without saving it.
'
Public WithEvents appWord As Word.Application
Private Sub appWord_DocumentBeforeClose(ByVal Doc As Document, Cancel As Boolean)
' Is this the file to be closed without saving?
If Doc.Name = gblThisDoc Then
ActiveDocument.Close SaveChanges:=False ' Close the file without saving it
End If
End Sub
创建模块如下:
Dim X As New EventClassModule 'Stores the object
Public gblThisDoc As String 'Stores the name of the file
'
' This sub initialises the application event handler
Public Sub RegisterEventHandler()
Set X.appWord = Word.Application
gblThisDoc = ActiveDocument.Name
End Sub
在此文档中:
Private Sub Document_Open()
RegisterEventHandler 'Start processing application events
End Sub