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.
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".
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With