excel - 对工作表进行拼写检查然后在不删除规则的情况下将其锁定的宏
问题描述
我有一个宏可以解锁我的 excel 文档、拼写检查,然后锁定工作表。但是,在锁定工作表后,它会删除有关用户可以在锁定的电子表格中做什么的规则(例如:添加/删除行、更改框的高度/宽度等)
之后我尝试列出规则,.Protect Password
但它不起作用。
Sub ProtectSheetCheckSpellCheck()
'Update by Extendoffice 2018/11/2
Dim xRg As Range
On Error Resume Next
Application.ScreenUpdating = False
With ActiveSheet
.Unprotect ("Password123")
Set xRg = .UsedRange
xRg.CheckSpelling
.Protect Password:="Password123", AllowInsertingRows:=True, AllowInsertingColumns:=True
End With
Application.ScreenUpdating = True
End Sub
解决方案
您正在寻找的是能够修改您的工作表而不实际取消保护它。您可以保护工作表,但允许 VBA 进行更改,而用户不能:
ActiveSheet.Protect UserInterfaceOnly:=True
https://docs.microsoft.com/en-us/office/vba/api/excel.worksheet.protect
名称:UserInterfaceOnly
说明:True 保护用户界面,但不保护宏。如果省略此参数,则保护适用于宏和用户界面。
这假定当工作表首先受到保护时该选项设置为 True。
或者,您可以将当前保护设置的状态存储在Protection
对象中:
Dim myProtection as Protection
Set myProtection = ActiveSheet.Protection
看起来像这样:请注意,由于某些原因.AllowEditRanges
,读取时会返回错误,因此我没有将其包含在列表中。
Sub test()
'Pick your Worksheet
Dim mySheet As Worksheet
Set mySheet = ActiveSheet
'Unprotect it
Dim myProtection As Protection
Set myProtection = mySheet.Protection
mySheet.Unprotect
'Do your VBA things
'Re Protect it
With myProtection
mySheet.Protect AllowFormattingCells:=.AllowFormattingCells, _
AllowFormattingColumns:=.AllowFormattingColumns, _
AllowFormattingRows:=.AllowFormattingRows, _
AllowInsertingColumns:=.AllowInsertingColumns, _
AllowInsertingRows:=.AllowInsertingRows, _
AllowInsertingHyperlinks:=.AllowInsertingHyperlinks, _
AllowDeletingColumns:=.AllowDeletingColumns, _
AllowDeletingRows:=.AllowDeletingRows, _
AllowSorting:=.AllowSorting, _
AllowFiltering:=.AllowFiltering, _
AllowUsingPivotTables:=.AllowUsingPivotTables
End With
End Sub
注意:.Protect
包括 [DrawingObjects]、[Scenarios] 和 [USerInterfaceOnly],而这些设置不是由Protection
对象提供的。我知道 [Contents] 参数应该与 相关.AllowEditRanges
,但由于无法访问它,我想它也会被跳过,
推荐阅读
- git - 如何防止 git 打包目标文件?
- python - 如何在函数类中保存临时数据?
- c++ - 为什么初始化 char*[] 需要 const 而 string[] 不需要?
- lua - 匹配字符串中所有小写字母的模式
- spring-boot - Netflix-zuul 无法在 docker 中路由 Spring Boot 微服务 API
- scala - Operator < 似乎不支持“Any”类型如何解决?
- sql - 子查询连接唯一ID来命名麻烦
- typescript - 类定义的双重断言
- c# - 使用 XDocument 解析 xml 文档
- html - CSS:100%表格的中心文本区域