closures工作表之前的消息框,以dislpay所有不受保护的工作表的名称

到目前为止,我已经完成了2个单独的编程。

在closures工作簿之前,会显示一个消息框:

Private Sub Workbook_BeforeClose(Cancel As Boolean) Dim answer As String Dim question As String question = "Display all the sheets which are Unprotected" answer = MsgBox(question, vbYesNo) If answer = vbNo Then MsgBox "complete everything and then close" Cancel = True Exit Sub Else ThisWorkbook.Save End If End Sub 

另一个显示在所有未受保护的工作表的新工作表“不受保护”中。

 Sub UnprotectSheet() Dim ws As Worksheet, a As Range ActiveWorkbook.Worksheets.Add.Name = "Unprotected" For Each ws In ActiveWorkbook.Worksheets If ws.ProtectContents = False And ws.Name <> "Unprotected" Then CNT = Sheets("Unprotected").Cells(Sheets("Unprotected").Rows.Count, "A").End(xlUp).Row Sheets("Unprotected").Cells(CNT + 1, "A") = ws.Name End If Next End Sub 

我想要一个消息框出现,如果我尝试closures工作表,如果任何工作表是不受保护的,消息框显示未受保护的工作表的名称。我在结合上述2代码面临问题。 我不是一个VBA专家,我正在尝试,但无法解决它。 任何援助将不胜感激。

像这样的东西可以显示你不受保护的床单清单。 但是,使用VBA强制保护可能更好,而不是提示用户这样做(除非需要为保护状态提供密码)。

  Private Sub Workbook_BeforeClose(Cancel As Boolean) Dim answer As String Dim question As String Dim unprotected as String unprotected = GetUnprotectedSheets(ThisWorkbook) If unprotected <> vbNullString Then MsgBox "Please protected the following worksheets before closing" & vbCRLF & unprotected Cancel = True Exit Sub Else ThisWorkbook.Save End If End Sub Function GetUnprotectedSheets(wb as Workbook) 'Custom function to return a string of sheet names ' which are unprotected Dim ret as String Dim ws as Worksheet For each ws in wb.Worksheets If Not ws.ProtectContents Then ret = IIF(ret = "", ws.Name, ret & vbCRLF & ws.Name) End If Next GetUnprotectedSheets = ret End Function 

您可以调用这样的程序来确保所有表单都受到保护:

 Sub ProtectAllSheets(wb as Workbook) Dim ws as Worksheet For each ws in wb.Worksheets If Not ws.ProtectContents Then ws.Protect Next End Sub 

只需在第二个脚本中添加一个计数器:

 Sub UnprotectSheet() Dim ws As Worksheet, a As Range Dim iCounter As Integer, strMessage As String 'Adding a counter variable & string 'ActiveWorkbook.Worksheets.Add.Name = "Unprotected" iCounter = 0 'Initialize it strMessage = "" 'Initialize empty string for the message box For Each ws In ActiveWorkbook.Worksheets If ws.ProtectContents = False Then iCounter = iCounter + 1 'Keeping track of any unprotected sheet ' CNT = Sheets("Unprotected").Cells(Sheets("Unprotected").Rows.Count, "A").End(xlUp).Row ' Sheets("Unprotected").Cells(CNT + 1, "A") = ws.Name strMessage = strMessage & ws.Name & " " End If Next ' Here you can do your msgbox or any other action if unprotected sheet detected If iCounter > 0 Then MsgBox ("These sheets are unprotected: " & strMessage) End If End Sub 

编辑:

要将其包含在button中,请单击:向您的表单添加一个activeXbutton,然后:

 Private Sub CommandButton1_Click() 'Eg make the sub a commmandbutton_click() event End Sub 

其实,当你添加button到你的表单时,如果你右键点击它,你可以select“查看代码” – 这将创build一个关联的Commandbutton_click,就像我上面显示的那样。