在受保护的工作表中取消保护特定范围

时间:2018-12-16 09:19:06

标签: excel vba

我有一个工作表,需要向用户提供保护。

我要保护整个工作表,但要保留特定范围以免更改。

这是我的代码,它在行.Locked = false中返回运行时错误。

Sub Protect()
With main
    .Protect Password:=1234
    .Range("U:V").Locked = False
    .Range("AH:AH").Locked = False
End With

With bakaraWS
    .Protect Password:=1234
End With

If segmenWS = "" Then
    Exit Sub
Else
    With segmenWS
        .Protect Password:=1234
        .Range("E:E").Locked = False
        .Range("H:H").Locked = False
    End With
End If
End Sub

1 个答案:

答案 0 :(得分:1)

您必须先解锁单元格,然后再保护工作表或使用UserInterfaceOnly:= True参数保护工作表,以便VBA可以操纵锁定的工作表。

Sub Protect()

    With main
        .UnProtect Password:=1234
        .Range("U:V").Locked = False
        .Range("AH:AH").Locked = False
        .Protect Password:=1234
    End With

    With bakaraWS
        .Protect Password:=1234
    End With

    If segmenWS = "" Then
        Exit Sub
    Else
        With segmenWS
            .UnProtect Password:=1234
            .Range("E:E").Locked = False
            .Range("H:H").Locked = False
            .Protect Password:=1234
        End With
    End If

End Sub

如果要在不先取消保护VBA的情况下操作VBA,请使用此替代方法。

    With main
        .Protect Password:=1234, UserInterfaceOnly:=True
        .Range("U:V").Locked = False
        .Range("AH:AH").Locked = False
    End With