VBA Word changing command button properties prevents closing without save prompt

42 views Asked by At

I want to be able to close my MS Word 2021 document without being prompted to save it, and I have added the following code:

Sub Document_Close()
    ActiveDocument.Saved = True
End Sub

This works as expected i.e if I change the text of the document, and then close it, there is no prompt.

I also have an ActiveX command button on my document. When I click on the button, my VBA sets the forecolor to red as follows:

Sub CommandButton1_Click()
    Me.CommandButton1.ForeColor = vbRed
End Sub

This all works as expected. However, if I click the command button (and do nothing else), the Save prompt always appears when I close the document. It would appear that changing the command button property causes Word to force the Save prompt to be displayed.

Is there any way to change the color of the command button, and to be able to close the document without being prompted to save it?

1

There are 1 answers

0
engeeaitch On

The solution is to use the Application BeforeClose event as follows: Create a Class Module as follows:

'
' 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

Create a Module as follows:

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

In This.Document:

Private Sub Document_Open()

    RegisterEventHandler 'Start processing application events
    
End Sub