[英]Excel Worksheet protection, with VBA for the
I have VBA code that runs on the workbook open event to enable worksheet protection for all worksheets. 我有在工作簿打开事件上运行的VBA代码,以为所有工作表启用工作表保护。 Every other time I open the workbook the worksheet protection is not turned on.
每当我打开工作簿时,工作表保护都不会打开。 I am completely perplexed at what could cause this.
我完全困惑可能导致这种情况的原因。 The code is:
代码是:
Option Explicit
Private Sub Workbook_Open()
Dim WKS As Worksheet
Dim WBK As Workbook
Set WBK = ThisWorkbook
For Each WKS In WBK.worksheets
WKS.Protect Password:="xyz", UserInterfaceOnly:=True
Next WKS
WBK.Protect Password:="xyz"
End Sub
' This is the before close event to make sure the user menu tab is active on open.
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim wsCurrent As Worksheet
Dim WSNew As Worksheet
Dim WBK As Workbook
Dim WKS As Worksheet
Set WBK = ThisWorkbook
Set wsCurrent = ActiveSheet
application.DisplayAlerts = False
If wsCurrent.Name = "Menu" Then
For Each WKS In WBK.worksheets
WKS.Protect (PW())
Next WKS
WBK.Save
Else
Set WSNew = application.worksheets("Menu")
WBK.Unprotect (PW())
WSNew.Visible = True
wsCurrent.Visible = False
For Each WKS In WBK.worksheets
WKS.Protect (PW())
Next WKS
WBK.Save
End If
End Sub
'This is the PW function
Function PW()
PW = "xyz"
End Function
I discovered the source of my difficulties. 我发现了困难的根源。 I needed to unprotect the workbook at the beginning of the routine and then protect it at the end again.
我需要在例程开始时取消保护工作簿,然后在结束时再次保护它。 I was only protecting it at the end.
我只是在最后保护它。 The revised code is:
修改后的代码是:
Option Explicit
Private Sub Workbook_Open()
Dim WKS As Worksheet
Dim WBK As Workbook
Set WBK = ThisWorkbook
WBK.Unprotect Password:="xyz"
For Each WKS In WBK.worksheets
WKS.Protect Password:="xyz", UserInterfaceOnly:=True
Next WKS
WBK.Protect Password:="xyz"
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.