如何使用vba保护工作簿?
要保护工作簿,必须使用 VBA 的 PROTECT 方法。使用此方法,您可以使用密码,甚至无需密码即可启用工作簿保护。但是对于您使用的密码,您需要考虑一件事,那就是区分大小写。
Workbook.Protect "Password"- 指定要保护的工作簿。
- 点击并指向并从列表中选择保护方法,或者您可以点击“保护”。
- 输入您要设置的密码。
- 运行代码以保护工作簿。
在本教程中,我们将以不同的方式学习此方法,并学习如何取消工作簿保护。
有用的链接:运行宏–宏记录器– Visual Basic 编辑器–个人宏手册
使用密码保护工作簿
以下是您需要使用密码保护工作簿的代码。在此代码中,首先您有工作簿名称和密码保护方法。
Workbooks("Book1").Protect "test123"当我运行此代码时,它会锁定工作簿“Book1”。

无需密码即可保护工作簿
如果您想在没有密码的情况下保护工作簿,则应该忽略“密码”参数,就像下面的代码一样。
Workbooks("Book1").Protect如果您尝试保护已受密码保护的无密码工作簿,Excel 将显示一个对话框以输入该密码。
使用密码取消工作簿保护
同样,您可以使用 unprotect 方法取消对工作簿的保护,其代码如下所示。
Workbooks("Book1").Unprotect "test123"如果您尝试取消保护工作簿,则需要注意一件事
取消保护没有密码的工作簿
如果工作簿不受密码保护,则可以使用相同的方法而无需指定密码参数。
保护所有打开的工作簿
在下面的代码中,我们有一个 FOR EACH 循环来循环所有打开的工作簿,并使用相同的保护方法逐一保护每个工作簿。
'variable to use as a workbook Dim wb As Workbook 'loop through all the open workbooks For Each wb In Application.Workbooks 'condition to check workbook name If wb.Name <> "PERSONAL.XLSB" Then 'protect every workbook with a password wb.Protect "test123" End If Next wb End Sub由于我使用的是个人宏工作簿,因此我使用IF THEN ELSE 语句来忽略工作簿名称是否为“ personal.xlsb ”。还要确保你照顾好它。
保护关闭的工作簿
您还可以保护和取消保护保存到某个位置的已关闭工作簿。请看以下代码,我使用桌面位置来使用“test.xlsx”文件。
Sub vba_protect_workbook() 'declare varibale to use for the workbook Dim wb As Workbook 'open the workbook that you want to protect Set wb = Workbooks.Open("C:UsersDellDesktoptest.xlsx") 'turn off the screen-updating to _ done everything in the backend Application.ScreenUpdating = False 'protect the workbook wb.Protect 'close the workbook after protecting wb.Close SaveChanges = True 'turn off the screen-updating Application.ScreenUpdating = True End Sub上面的代码使用 Workbook.Open 方法打开要保护的工作簿,然后禁用屏幕更新以在后端工作。
保护文件夹中所有已关闭的工作簿
以下代码循环访问您指定为路径的文件夹中的所有工作簿。然后将每个活页夹打开、保护并一一合上。
Sub vba_protect_all_the_workbooks() 'declare variables Dim wb As Workbook Dim myPath As String Dim myFile As String Dim myExtension As String Dim FldrPicker As FileDialog 'optimize macro Application.ScreenUpdating = False Application.EnableEvents = False Application.Calculation = xlCalculationManual 'specify the folder where workbooks are saved myPath = "C:UsersDellDesktopfolder" 'jump to reset setting if there's an error On Error GoTo ResetSettings 'target file fxtension (must include wildcard "*") myExtension = "*.xls*" 'target path myFile = Dir(myPath & myExtension) 'Loop through each Excel file in folder Do While myFile <> "" 'Set variable equal to opened workbook Set wb = Workbooks.Open(Filename:=myPath & myFile) 'protect workbook wb.Protect 'Save and Close Workbook wb.Close SaveChanges:=True 'Get next file name myFile = Dir Loop 'Message Box when task is completed MsgBox "Done!" 'reset setting that were change for optimization ResetSettings: Application.EnableEvents = True Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub