Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BeforeClose VBA Event Closing Workbook When Cancel = True

Tags:

excel

vba

I'm trying to write a short macro that will prevent the user of an excel workbook from closing the workbook without protecting the first sheet.

The code shows the message box but then proceeds to close the workbook. From my understanding, if the "Cancel" parameter is set to True, the workbook shouldn't close.

Private Sub Workbook_BeforeClose(Cancel As Boolean)

    If Sheets(1).ProtectContents = True Then
        Cancel = False
    Else
        MsgBox "Please Protect 'Unique Futures' Worksheet Before Closing Workbook"
        Cancel = True
    End If    
End Sub

I just need the code to display the message box and then not close if the first sheet is not protected.

like image 447
Jarom Avatar asked Oct 18 '22 10:10

Jarom


People also ask

What does Cancel As Boolean mean?

Private Sub Workbook_BeforeClose(Cancel As Boolean) End Sub. The closing of the workbook can be cancelled by assigning the value True to the variable "Cancel".

How do I close a specific workbook in VBA?

Steps to Close a Workbook Specify the workbook that you want to close. Use the close method with that workbook. In the code method, specify if you want to save the file or not. In the end, mention the location path where you want to save the file before closing.


1 Answers

I could replicate it if I set Application.EnableEvents to False. In the below example I have remembered its state to place it back as was after, however, I'm not sure how it gets to a state of False to begin with.

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Dim BlnEventState as Boolean

    BlnEventState = Application.EnableEvents
    Application.EnableEvents = True

    If Sheets(1).ProtectContents = True Then
        Cancel = False
    Else
        MsgBox "Please Protect 'Unique Futures' Worksheet Before Closing Workbook"
        Cancel = True
    End If

    Application.EnableEvents = BlnEventState

End Sub

It may be a safer long term option to force the state rather then set it back.

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    Application.EnableEvents = True
    If Sheets(1).ProtectContents = True Then
        Cancel = False
    Else
        MsgBox "Please Protect 'Unique Futures' Worksheet Before Closing Workbook"
        Cancel = True
    End If    
End Sub
like image 121
Gary Evans Avatar answered Nov 15 '22 06:11

Gary Evans