2010 Excel VBA – 如果工作簿已被保护结束小组问题

我有一个使用下面的子ProtectAll_ADMIN()代码的button。

管理按钮

当pipe理员已经保护工作簿时,将会发生错误而不检查工作簿是否已经被保护。 所以我想要一个消息框告诉pipe理员,工作簿已经被保护了。 下面的代码会告诉我,即使它没有被保护,它也已经被保护了。 如果我去掉下面的代码行,它会运行正常,但我又回到了一个方块,它会出错,因为一个列已经隐藏了我的调用mcr_HideRowsColumns_ADMIN()。 即我想这个子例程分开,因为有很多表需要隐藏的列和行。

If ActiveWorkbook.ProtectStructure Then End MsgBox ActiveWorkbook.Name & " is already protected.", _ vbCritical Exit Sub 

下面是整个代码,我真的很感激别人敏锐的眼光:

 Sub ProtectAll_ADMIN() Dim S As Object If ActiveWorkbook.ProtectStructure Then End MsgBox ActiveWorkbook.Name & " is already protected.", _ vbCritical Exit Sub ' To Hide all rows and columns for editing Call mcr_HideRowsColumns_ADMIN Dim pWord1 As String, pWord2 As String pWord1 = InputBox("Please Enter the password") If pWord1 = "" Then Exit Sub pWord2 = InputBox("Please re-enter the password") If pWord2 = "" Then Exit Sub 'Make certain passwords are identical If InStr(1, pWord2, pWord1, 0) = 0 Or _ InStr(1, pWord1, pWord2, 0) = 0 Then MsgBox "You entered different passwords. No action taken!" Exit Sub End If For Each ws In Worksheets ws.Protect Password:=pWord1 Next MsgBox "All Sheets are Protected." Exit Sub '------------------------------------------- Sheets("Home").Select Range("A1").Select End Sub 

有什么想法吗? 谢谢!

我稍微重新devise了你的代码:

 Sub ProtectAll_ADMIN() Dim ws As Worksheet Dim pWord1 As String Dim pWord2 As String For Each ws In Worksheets If ws.ProtectContents Then MsgBox ActiveWorkbook.Name & " is already protected.", vbCritical Exit Sub End If Next ws ' To Hide all rows and columns for editing Call mcr_HideRowsColumns_ADMIN pWord1 = InputBox("Please Enter the password") If pWord1 = "" Then Exit Sub pWord2 = InputBox("Please re-enter the password") If pWord2 = "" Then Exit Sub 'Make certain passwords are identical If InStr(1, pWord2, pWord1, 0) = 0 Or InStr(1, pWord1, pWord2, 0) = 0 Then MsgBox "You entered different passwords. No action taken!" Exit Sub End If For Each ws In Worksheets ws.Protect Password:=pWord1 Next MsgBox "All Sheets are Protected." End Sub