如何在 VBA 中锁定 Excel 单元格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17111648/
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
How to lock Excel cells in VBA?
提问by Analytic Lunatic
I have an Excel worksheet that acts like an application, with form control buttons allowing users to 'navigate' through records. First, Previous, Next & Last cycle appropriately through one of the worksheets records, displaying the values in my 'form' worksheet.
我有一个 Excel 工作表,它的作用类似于一个应用程序,带有表单控制按钮,允许用户“浏览”记录。首先、上一个、下一个和最后一个适当地循环通过其中一个工作表记录,在我的“表单”工作表中显示值。
When users are not in Edit or Add Mode, I would like to lock the cells to prevent users from modifying contents.
当用户不在编辑或添加模式时,我想锁定单元格以防止用户修改内容。
I tried Range("A1:O24").Locked = True, but I am still able to type new values into the cells.
我尝试了 Range("A1:O24").Locked = True,但我仍然能够在单元格中键入新值。
Anyone know how to accomplish this? I need my vba code to be able to assign new values to the cells as users 'navigate', but to prevent users from entering new values unless in Add or Edit mode.
有谁知道如何做到这一点?我需要我的 vba 代码才能在用户“导航”时为单元格分配新值,但要防止用户输入新值,除非处于“添加”或“编辑”模式。
回答by SELECTCOUNTSTAR
I believe the reason for this is that you need to protect a worksheet before cells actually become locked. All cells are formatted as locked as a default so what you really want to do is set the range that you don't want locked to Range().Locked = False and then set the worksheet to protected.
我相信这样做的原因是您需要在单元格实际被锁定之前保护工作表。所有单元格的格式都设置为默认锁定,因此您真正想要做的是将您不想锁定的范围设置为 Range().Locked = False,然后将工作表设置为受保护。
In the case that you want all cells locked all you have to do is set the worksheet to protected
如果您希望所有单元格被锁定,您只需将工作表设置为受保护
回答by Milan Sheth
Search for your condition whether user was not in Edit or Add mode and then locking your range and finally protect your worksheet.
搜索您的条件,无论用户是否处于编辑或添加模式,然后锁定您的范围并最终保护您的工作表。
Let's say for example in one case, if you want to locked cells from range A1 to I50 then below is the code:
例如,在一种情况下,如果您想锁定范围 A1 到 I50 的单元格,那么下面是代码:
Worksheets("Enter your sheet name").Range("A1:I50").Locked = True
ActiveSheet.Protect Password:="Enter your Password"
In another case if you already have a protected sheet then follow below code:
在另一种情况下,如果您已经有一个受保护的工作表,请按照以下代码操作:
ActiveSheet.Unprotect Password:="Enter your Password"
Worksheets("Enter your sheet name").Range("A1:I50").Locked = True
ActiveSheet.Protect Password:="Enter your Password"