Vba excel как заблокировать ячейки в excel

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.

asked Jun 14, 2013 at 15:09

Analytic Lunatic's user avatar

Analytic LunaticAnalytic Lunatic

3,84522 gold badges76 silver badges119 bronze badges

2

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

answered Jun 14, 2013 at 15:13

SELECTCOUNTSTAR's user avatar

1

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"

answered Sep 18, 2013 at 9:34

Milan Sheth's user avatar

Milan ShethMilan Sheth

84412 silver badges10 bronze badges

Как правило, вам необходимо защитить весь рабочий лист, чтобы заблокировать ячейки от редактирования. Есть ли способ заблокировать ячейки без защиты всего рабочего листа? Эта статья рекомендует вам метод VBA.

Блокируйте указанные ячейки без защиты всего рабочего листа с помощью VBA


Блокируйте указанные ячейки без защиты всего рабочего листа с помощью VBA

Предположим, вам нужно заблокировать ячейки A3 и A5 на текущем листе, следующий код VBA поможет вам добиться этого, не защищая весь лист.

1. Щелкните правой кнопкой мыши вкладку листа и выберите Просмотреть код из контекстного меню.

2. Затем скопируйте и вставьте приведенный ниже код VBA в окно кода. Смотрите скриншот:

Код VBA: блокировка указанных ячеек без защиты всего рабочего листа

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Column = 1 Then
        If Target.Row = 3 Or Target.Row = 5 Then
            Beep
            Cells(Target.Row, Target.Column).Offset(0, 1).Select
        End If
    End If
End Sub

Внимание: В коде Колонка 1, Ряд = 3 и Ряд = 5 указывает, что ячейки A3 и A5 на текущем листе будут заблокированы после запуска кода. Вы можете изменить их по своему усмотрению.

3. нажмите другой + Q клавиши одновременно, чтобы закрыть Microsoft Visual Basic для приложений окно.

Теперь ячейки A3 и A5 заблокированы на текущем листе. Если вы попытаетесь выбрать ячейку A3 или A5 на текущем листе, курсор автоматически переместится в правую соседнюю ячейку.


Статьи по теме:

  • Как заблокировать сразу все ссылки на ячейки в формулах в Excel?
  • Как заблокировать или защитить ячейки после ввода данных или ввода в Excel?
  • Как заблокировать или разблокировать ячейки на основе значений в другой ячейке в Excel?
  • Как заблокировать изображение / изображение в ячейке или внутри нее в Excel?
  • Как заблокировать ширину и высоту ячейки от изменения размера в Excel?

Лучшие инструменты для работы в офисе

Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%

  • Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
  • Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон
  • Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы… Предотвращение дублирования ячеек; Сравнить диапазоны
  • Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
  • Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
  • Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии
  • Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
  • Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF
  • Более 300 мощных функций. Поддерживает Office/Excel 2007-2021 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.

вкладка kte 201905


Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!

офисный дно

Комментарии (22)


Оценок пока нет. Оцените первым!

 

Marshal

Пользователь

Сообщений: 83
Регистрация: 27.12.2012

#1

18.10.2016 02:18:33

Доброго времени.
Для защиты ячеек использую код ниже.

Но данная защита снимается нажатием правой кнопкой на листе «Снять защиту листа».
Что можно сделать дабы исключить такую возможность вообще или снятие через пароль, но на VBA.

Всем спасибо

Код
Private Sub Workbook_Open()
   Cells.Locked = False '
    Range("F5:AH5").Locked = True
    ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True
End Sub

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

#2

18.10.2016 02:22:31

Код
Protect("abracadabra")
Unprotect("abracadabra")
 

Marshal

Пользователь

Сообщений: 83
Регистрация: 27.12.2012

Спасибо за ответ. с этим я и воююю
Не могу прикрутить

 

k61

Пользователь

Сообщений: 2441
Регистрация: 21.12.2012

#4

18.10.2016 02:51:08

Прикрутка:

Код
....
ActiveSheet.Protect Password:="abracadabra", DrawingObjects:.......
....
 

Marshal

Пользователь

Сообщений: 83
Регистрация: 27.12.2012

#5

18.10.2016 04:25:06

Спасибо большое, прикрутил.
Не знаю на сколько правильно. Все ячейки кроме указанных не заблокированы.

Код
Private Sub Workbook_Open()
 Sheets("Лист1").Select
ActiveSheet.Unprotect Password:="321"
    Range("B8:AH8").Locked = True
    ActiveSheet.Protect Password:="321"
End Sub

I want to stop others from editing the cell contents in my excel sheet using VBA. Is it possible to do this?

armstrhb's user avatar

armstrhb

4,0243 gold badges20 silver badges28 bronze badges

asked Jun 14, 2010 at 13:05

raam's user avatar

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 Roberts's user avatar

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 McCormack's user avatar

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 Sheth's user avatar

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

Fink's user avatar

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

krusaint's user avatar

This macro allows you to have a cell automatically locked after a user enters something into it or into another specific cell, range, column, or row.

This is different than just locking an entire spreadsheet because you still want to be able to edit and work with the other cells in the worksheet without having to select and unlock them individually.

Sections:

Unlock the Cells

Macro to Auto-Lock Cells

Lock a Specific Cell

Lock Cell Other Than the One that was Edited

Lock Last Edited Cell

Lock Cell in a Specific Column or Row

Notes

Unlock the Cells

The first thing you have to do is to unlock all of the cells in the worksheet.

  1. Select all of the cells by hitting Ctrl + A or clicking the square next to row 1 and column A.
    968a451bf4d079c06ac431ee01733aa8.png
  2. Right click in the worksheet and choose Format Cells
    d1c63c00618f078970fe3f0387354bc4.png
  3. Go to the Protection tab and uncheck the Locked option at the top.
    216c4387e60b7cab5825e41c909de4ef.png
  4. Hit OK and you’re done with this part.

Now, none of the cells in the worksheet are protected, which means that all of the cells in the worksheet will be editable when you go to protect the worksheet.

This needs to be done so that only specific cells that we choose will be locked from editing.

Macro to Auto-Lock Cells

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Address = "$A$1" And Target.Value <> "" Then

    ActiveSheet.Protect Contents:=False
    Range(Target.Address).Locked = True
    ActiveSheet.Protect Contents:=True

End If

End Sub

The important code is this part:

ActiveSheet.Protect Contents:=False
Range(Target.Address).Locked = True
ActiveSheet.Protect Contents:=True

It unprotects the worksheet, locks the cell, and then re-protects the sheet.

This macro needs to be installed into the worksheet where it will run. To do this, right-click the tab of the desired worksheet and click View Code and paste the macro into the window that opens.

This example is a generic example that is easy to modify. It checks which cell was edited and, if a certain cell was edited, it is then locked.

I will show you how to edit this macro in the examples below.

Lock a Specific Cell

Looking at the macro above, this is the line that limits the macro to run only on specific cells:

If Target.Address = "$A$1" And Target.Value <> "" Then

This says that a cell should be locked only if cell A1 was edited and it is not empty.

To make the macro work on cell B1 or D15 or any cell, just replace $A$1 with the desired cell reference. You must put dollar signs in front of the column and row reference for this to work.

You can also lock the cell only if a certain value was input by changing <> «» in the line above to = «desired value» and that allows you to do something like lock the cell only if OK was entered or something similar.

Lock Cell Other Than the One that was Edited

Change this line:

Range(Target.Address).Locked = True

Target.Address is the cell that will be locked and this says to lock the cell that was just edited.

To lock another cell, just use the Range method of referencing cells.

To lock cell B5, it would be Range(B5).Locked = True

Continue that pattern for whichever cell or range you want to lock.

Lock Last Edited Cell

You can lock the last edited cell regardless of which one it was by removing the IF statement in the macro and leaving it like this:

Private Sub Worksheet_Change(ByVal Target As Range)

ActiveSheet.Protect Contents:=False
Range(Target.Address).Locked = True
ActiveSheet.Protect Contents:=True

End Sub

Lock Cell in a Specific Column or Row

To limit the locking to a certain column or row, change the IF statement.

Limit to a row:

If Target.Row = 1 And Target.Value <> "" Then

Change the 1 to whichever row you want and the code will only run on that row.

Limit to a Column:

If Target.Column = 1 And Target.Value <> "" Then

Change the 1 to whichever column you want the code to run on.

Notes

This is a handy macro that allows you to have a lot of control over a worksheet and protecting the data within it.

I didn’t show you how to password protect the worksheet here because I wanted to focus on the method needed to protect only specific cells. Once you get this form of the macro running well, then, add-in the other pieces that you want, like password protection.

Make sure to download the sample file attached to this tutorial so you can work with these examples in Excel.

Similar Content on TeachExcel

Email List of People from Excel Using a Macro

: Send Emails from Excel Course
Send emails to everyone in a list in Excel using a macro. Th…

Loop through a Range of Cells in Excel VBA/Macros

Tutorial: How to use VBA/Macros to iterate through each cell in a range, either a row, a column, or …

Select Cells in Excel using Macros and VBA

Tutorial: This is actually a very easy thing to do and only requires a couple lines of code. Below I…

Select Ranges of Cells in Excel using Macros and VBA

Tutorial: This Excel VBA tutorial focuses specifically on selecting ranges of cells in Excel.  This…

Allow Only Certain People to Edit Specific Cells in Excel

Tutorial:
How to allow only certain people to edit certain cells or ranges in Excel.

This is a sec…

Add a Drop Down Menu to a Cell in Excel — Data Validation Macro

Macro: Add a drop down menu or list to a cell in Excel with this free Excel macro. This is a grea…

Subscribe for Weekly Tutorials

BONUS: subscribe now to download our Top Tutorials Ebook!

Понравилась статья? Поделить с друзьями:
  • Vba excel как добавить столбец
  • Vba excel как добавить колонку
  • Vba excel как добавить кнопку на лист excel
  • Vba excel как вызвать форму
  • Vba excel как вызвать процедуру