使用 VBA 取消对单元格的保护

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39755017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 11:20:43  来源:igfitidea点击:

Using VBA to unprotect cells

excel-vbacellsprotectionvbaexcel

提问by Karen Hornsby

So I have a spreadsheet that I want to format based on user inputs, but the cells need to remain locked until it is determined by the formatting that they will be user input cells. I have code that will look the cells for the user interface only but allow VBA to edit them.

所以我有一个电子表格,我想根据用户输入设置格式,但单元格需要保持锁定状态,直到由格式确定它们将成为用户输入单元格。我有代码只会查看用户界面的单元格,但允许 VBA 编辑它们。

> 'protects all sheets upon opening work book
>     Me.Worksheets("Sheet1").Protect "Password", UserInterfaceOnly:=True
>     Me.Worksheets("Sheet2").Protect "Password", UserInterfaceOnly:=True
>     Me.Worksheets("Sheet3").Protect "Password", UserInterfaceOnly:=True

so now I need to allow the following cells to be editable by the user

所以现在我需要允许用户编辑以下单元格

Sheets("Sheets2").Protection.AllowEditRanges.Add "Test", Range("C2", "C8")
Sheets("Sheets2").Protection.AllowEditRanges.Add "Test", Range("H6")
Sheets("Sheets2").Protection.AllowEditRanges.Add "Test", Range("K6")

I have tried allowing edits before I lock the sheet and after. What I'd really like is some VBA code to unlock the cells after applying formatting rather than defining which cells might be editable in advance. Any help gratefully appreciated :)

我曾尝试在锁定工作表之前和之后允许编辑。我真正喜欢的是一些 VBA 代码,可以在应用格式后解锁单元格,而不是提前定义哪些单元格可以编辑。感谢任何帮助:)

回答by Werrf

Change the Lockedproperty of the range.

更改Locked范围的属性。

Range("C2", "C8").Locked = false

This is equivalent to using the Format Cells | Protection | Locked checkbox to remove protection from a cell, and will make the cell immediately available for editing.

这等效于使用 Format Cells | 保护 | 锁定复选框以取消对单元格的保护,并使该单元格立即可用于编辑。

Also, for future use, you may want to think about adding a simple loop to the protection step:

此外,为了将来使用,您可能需要考虑在保护步骤中添加一个简单的循环:

Dim sht as Worksheet

For each sht in ThisWorkbook.Sheets
    sht.protect password:=Password, Userinterfaceonly:=True
Next sht

That way people can't get around the restriction by adding new sheets, and the protection will continue to work if sheets are renamed, etc.

这样人们就无法通过添加新工作表来绕过限制,如果工作表被重命名等,保护将继续有效。