BeforeClose VBA Event Closing Workbook When Cancel = True

筅森魡賤 提交于 2020-01-14 12:54:12

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/36896555/beforeclose-vba-event-closing-workbook-when-cancel-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!