How to lock Excel cells in VBA?

感情迁移 提交于 2019-12-25 01:47:00

问题


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.

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.

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.


回答1:


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.

In the case that you want all cells locked all you have to do is set the worksheet to protected




回答2:


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:

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"


来源:https://stackoverflow.com/questions/54636470/vba-how-to-lock-only-certain-columns-in-a-sheet-based-on-date

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