Excel VBA: Sheet protection not working as desired

一世执手 提交于 2019-12-24 16:17:40

问题


Using VBA I'm trying to disallow insertion and deletion of rows and columns while allowing the user to edit cell contents. I was hoping the following call would do the trick:

ActiveSheet.Protect Password:="SomePassword", _
AllowInsertingColumns:=False, AllowInsertingRows:=False, _
AllowDeletingColumns:=False, AllowDeletingRows:=False, Contents:=False

But this doesn't work as I expect. I can still insert and delete rows and columns.

What am I missing? What's the correct way to achieve the above?


回答1:


I found the answer after a little more experimentation. Here's the code:

ActiveSheet.Cells.Locked = False
ActiveSheet.Protect Password:="SomePassword"

This sets the 'Locked' property of all cells in the sheet to 'False' and then protects the sheet fully. The reason it works is because protection disables editing only for those cells that have 'Locked' set to 'True'.




回答2:


It appears that AllowInsertingRows etc. are options that are only available if you lock down the contents with Contents:=True. This is not made clear in the Help information.

As you want contents to be editable, you're have to mark all cells that you want editable as unlocked (set cell or range property Locked to false). Then use Protect with Contents:=True.




回答3:


As far as I can tell, you need Contents:=True in order for everything else to work! Of course, this goes against your need for users to be able to edit the content of cells... locked cells, that is. So just unlock all your cells (Format|Protection|uncheck the Locked tickbox) prior to protecting the sheet.



来源:https://stackoverflow.com/questions/5620902/excel-vba-sheet-protection-not-working-as-desired

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!