excel – BeforeClose VBA事件关闭工作簿当Cancel = True时

我正在尝试编写一个简短的宏,它将阻止excel工作簿的用户关闭工作簿而不保护第一个工作表.

代码显示消息框,但然后继续关闭工作簿.根据我的理解,如果“取消”参数设置为True,则不应关闭工作簿.

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

我只需要代码显示消息框,然后如果第一张表没有受到保护则不关闭.

最佳答案 如果我将Application.EnableEvents设置为False,我可以复制它.在下面的例子中,我记得它的状态是把它放回原来的状态,但是,我不确定它是如何以一个False的状态开始的.

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

强迫国家而不是将其重新定位可能是一个更安全的长期选择.

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
点赞