I want to stop others from editing the cell contents in my excel sheet using VBA. Is it possible to do this?
armstrhb
4,0243 gold badges20 silver badges28 bronze badges
asked Jun 14, 2010 at 13:05
1
You can first choose which cells you don’t want to be protected (to be user-editable) by setting the Locked status of them to False:
Worksheets("Sheet1").Range("B2:C3").Locked = False
Then, you can protect the sheet, and all the other cells will be protected.
The code to do this, and still allow your VBA code to modify the cells is:
Worksheets("Sheet1").Protect UserInterfaceOnly:=True
or
Call Worksheets("Sheet1").Protect(UserInterfaceOnly:=True)
answered Jun 14, 2010 at 17:31
Lance RobertsLance Roberts
22.2k32 gold badges112 silver badges129 bronze badges
5
Try using the Worksheet.Protect method, like so:
Sub ProtectActiveSheet()
Dim ws As Worksheet
Set ws = ActiveSheet
ws.Protect DrawingObjects:=True, Contents:=True, _
Scenarios:=True, Password="SamplePassword"
End Sub
You should, however, be concerned about including the password in your VBA code. You don’t necessarily need a password if you’re only trying to put up a simple barrier that keeps a user from making small mistakes like deleting formulas, etc.
Also, if you want to see how to do certain things in VBA in Excel, try recording a Macro and looking at the code it generates. That’s a good way to get started in VBA.
answered Jun 14, 2010 at 13:54
Ben McCormackBen McCormack
31.8k46 gold badges145 silver badges221 bronze badges
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"
answered Sep 18, 2013 at 9:40
Milan ShethMilan Sheth
84412 silver badges10 bronze badges
You can also do it on the worksheet level captured in the worksheet’s change event. If that suites your needs better. Allows for dynamic locking based on values, criteria, ect…
Private Sub Worksheet_Change(ByVal Target As Range)
'set your criteria here
If Target.Column = 1 Then
'must disable events if you change the sheet as it will
'continually trigger the change event
Application.EnableEvents = False
Application.Undo
Application.EnableEvents = True
MsgBox "You cannot do that!"
End If
End Sub
answered Jun 15, 2010 at 15:28
FinkFink
3,31619 silver badges26 bronze badges
Sub LockCells()
Range("A1:A1").Select
Selection.Locked = True
Selection.FormulaHidden = False
ActiveSheet.Protect DrawingObjects:=False, Contents:=True, Scenarios:= False, AllowFormattingCells:=True, AllowFormattingColumns:=True, AllowFormattingRows:=True, AllowInsertingColumns:=True, AllowInsertingRows:=True, AllowInsertingHyperlinks:=True, AllowDeletingColumns:=True, AllowDeletingRows:=True, AllowSorting:=True, AllowFiltering:=True, AllowUsingPivotTables:=True
End Sub
answered Jun 14, 2010 at 21:41
|
Владимир С Пользователь Сообщений: 50 |
Добрый день. Прошу помощи в реализации запрета на изменения данных в в ячейке или диапазоне ячеек. Данный запрет должен быть реализован только макросом. Стандартные методы не подходят. |
|
Пытливый Пользователь Сообщений: 4586 |
Добрый. Кому решение нужно — тот пример и рисует. |
|
The_Prist Пользователь Сообщений: 14181 Профессиональная разработка приложений для MS Office |
#3 17.12.2015 13:39:11
вот с этого момента поподробнее. А если я отключу работу макросов — что делать будете? Просто странное желание: не защитить нормально, а именно макросом. Поэтому хочется услышать цель, а не хотелку.
Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||||
|
Владимир С Пользователь Сообщений: 50 |
Есть определенный функционал(надстройка) который выполняет определенный действия ссылаясь на выделенную ячейку, запрещать стандартным способом изменения можно, но тогда остается возможность пользователю копировать все данные с листа, а это должно быть запрещено. Когда стоит запрет на выделение заблокированы ячеек тогда функционал не может работать так как не видит выделенные для него ячейки. |
|
Владимир С Пользователь Сообщений: 50 |
#5 17.12.2015 13:53:15
Стоит двойная защита листа для пользователя, как макросом, макросы работаю но лист остается защищен и ручная защита стандартным способом. Если отключить работу макросов тогда пользователь ничего не сделает что от него требуется. Изменено: Владимир С — 17.12.2015 14:19:19 |
||
|
The_Prist Пользователь Сообщений: 14181 Профессиональная разработка приложений для MS Office |
#6 17.12.2015 14:06:53
так цель запретить копировать данные?
? Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||||
|
Владимир С Пользователь Сообщений: 50 |
#7 17.12.2015 14:07:00
Код супер но он запрещает изменение все ячеек, а как указать диапазон который нужно запретить? |
||
|
The_Prist Пользователь Сообщений: 14181 Профессиональная разработка приложений для MS Office |
#8 17.12.2015 14:09:20
вставить перед With Application Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
|
Владимир С Пользователь Сообщений: 50 |
|
|
Владимир С Пользователь Сообщений: 50 |
#10 17.12.2015 14:18:39
Да, этот способ проще для реализации защиты от копирования, а также защита от изменений. |
||
|
Запрет изменения ячейки по условию |
||||||||
Ответить |
||||||||
Ответить |
You can modify a sheet via code by taking these actions
- Unprotect
- Modify
- Protect
In code this would be:
Sub UnProtect_Modify_Protect()
ThisWorkbook.Worksheets("Sheet1").Unprotect Password:="Password"
'Unprotect
ThisWorkbook.ActiveSheet.Range("A1").FormulaR1C1 = "Changed"
'Modify
ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password"
'Protect
End Sub
The weakness of this method is that if the code is interrupted and error handling does not capture it, the worksheet could be left in an unprotected state.
The code could be improved by taking these actions
- Re-protect
- Modify
The code to do this would be:
Sub Re-Protect_Modify()
ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password", _
UserInterfaceOnly:=True
'Protect, even if already protected
ThisWorkbook.ActiveSheet.Range("A1").FormulaR1C1 = "Changed"
'Modify
End Sub
This code renews the protection on the worksheet, but with the ‘UserInterfaceOnly’ set to true. This allows VBA code to modify the worksheet, while keeping the worksheet protected from user input via the UI, even if execution is interrupted.
This setting is lost when the workbook is closed and re-opened. The worksheet protection is still maintained.
So the ‘Re-protection’ code needs to be included at the start of any procedure that attempts to modify the worksheet or can just be run once when the workbook is opened.


