VBA: 为worksheet 设置密码和解除密码 |
您所在的位置:网站首页 › excel锁定怎么输入密码 › VBA: 为worksheet 设置密码和解除密码 |
文章背景: 在工作中,有时候需要给工作表的的内容设置保护,避免数据被误修改,同时又希望可以通过宏命令,实现数据处理的自动化。此时,我们可以在宏命令中添加相应的代码:在程序执行前,解除密码;在程序结束后,设置密码。 1 判断工作表是否处于保护状态ProtectContents是工作表的属性,用于判断工作簿中的某张表是否处于保护状态。 语法:expression.ProtectContents expression: A variable that represents a Worksheet object.True if the contents of the sheet are protected.代码示例: 代码语言:javascript复制If Worksheets("Sheet1").ProtectContents = True Then MsgBox "The contents of Sheet1 are protected." End If2 保护和解除保护工作表2.1 保护工作表在VBA中可以使用Worksheet对象的Protect方法保护工作表。 语法:expression.Protect (Password, DrawingObjects, Contents, Scenarios, UserInterfaceOnly, AllowFormattingCells, AllowFormattingColumns, AllowFormattingRows, AllowInsertingColumns, AllowInsertingRows, AllowInsertingHyperlinks, AllowDeletingColumns, AllowDeletingRows, AllowSorting, AllowFiltering, AllowUsingPivotTables) expression: A variable that represents a Worksheet object.Protects a worksheet so that it cannot be modified.参数的具体使用见文末的参考资料[5]。Protect方法的所有参数都是可选的;Password参数可以不提供,表示没有设置密码保护excel工作表。其余的部分参数对应的是“保护工作表”对话框中显示的“允许此工作表的所有用户进行的选项”,如下图所示: 值得一提的是,在保护工作表之前,需要对受保护的单元格区域设置锁定。这样,在保护工作表期间,那些锁定单元格得到保护,其他未锁定的单元格依然可以编辑。 2.2 解除保护工作表在VBA中可以使用Worksheet对象的Unprotect方法解除保护工作表。 语法:expression.Unprotect (Password) expression: A variable that represents a Worksheet object.Removes protection from a sheet or workbook. This method has no effect if the sheet or workbook isn't protected.3 综合示例假设有张工作表Sheet1,密码是“111”,单元格区域已锁定。在数据处理前,解除密码保护;数据处理结束之后,再设置密码保护。 代码语言:javascript复制Option Explicit Sub EditData() '修改数据 Dim sht As Worksheet, flag_protect As Boolean Set sht = ThisWorkbook.Worksheets("Sheet1") flag_protect = False '1 取消密码保护 If sht.ProtectContents = True Then sht.Unprotect Password:="111" '撤消工作表保护并取消密码 flag_protect = True End If '2 修改数据 sht.Range("B3").Value2 = "30" '3 保护工作表并设置密码 If flag_protect Then sht.Protect Password:="111", Contents:=True, _ AllowFormattingCells:=True, AllowFormattingColumns:=True, _ AllowFormattingRows:=True End If MsgBox "Done!" End Sub参考资料: [1] vba 之判断工作表是否处于保护状态:Worksheets.ProtectContents(https://blog.csdn.net/ljr_123/article/details/106946830) [2] Worksheet.ProtectContents property (Excel)(https://learn.microsoft.com/en-us/office/vba/api/excel.worksheet.protectcontents) [3] VBA为worksheet 设置密码和解除密码(https://blog.csdn.net/weixin_44741335/article/details/105566561) [4] 如何用vba批量保护或取消保护excel工作表(http://www.exceloffice.net/archives/1293) [5] Worksheet.Protect method(https://learn.microsoft.com/en-us/office/vba/api/excel.worksheet.protect) [6] Worksheet.Unprotect method(https://learn.microsoft.com/en-us/office/vba/api/excel.worksheet.unprotect) |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |