首页 > 解决方案 > 对工作表进行拼写检查然后在不删除规则的情况下将其锁定的宏

问题描述

我有一个宏可以解锁我的 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

标签: excelvbaspell-checking

解决方案


您正在寻找的是能够修改您的工作表而不实际取消保护它。您可以保护工作表,但允许 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,但由于无法访问它,我想它也会被跳过,


推荐阅读