Перейти к основному содержанию

Как заблокировать или разблокировать ячейки на основе значений в другой ячейке в Excel?

В некоторых случаях вам может потребоваться заблокировать или разблокировать ячейки на основе значений в другой ячейке. Например, вам нужно, чтобы диапазон B1: B4 был разблокирован, если ячейка A1 содержит значение «Accepting»; и блокироваться, если ячейка A1 содержит значение «Отказано». Как вы можете этого добиться? Эта статья может вам помочь.

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


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

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

1. Щелкните правой кнопкой мыши вкладку листа (лист с ячейками, которые необходимо заблокировать или разблокировать на основе значений в другой ячейке) и нажмите Просмотреть код из контекстного меню.

2. Затем скопируйте и вставьте следующий код VBA в окно кода.

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

Private Sub Worksheet_Change(ByVal Target As Range)
    If Range("A1") = "Accepting" Then
        Range("B1:B4").Locked = False
    ElseIf Range("A1") = "Refusing" Then
        Range("B1:B4").Locked = True
    End If
End Sub

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

С этого момента, когда вы вводите значение «Принимаю» в ячейку A1, диапазон B1: B4 разблокируется.

При вводе значения «Отказано» в ячейку A1 указанный диапазон B1: B4 автоматически блокируется.


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

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

Популярные опции: Найдите, выделите или определите дубликаты   |  Удалить пустые строки   |  Объедините столбцы или ячейки без потери данных   |   Раунд без формулы ...
Супер поиск: Множественный критерий VLookup    VLookup с несколькими значениями  |   VLookup по нескольким листам   |   Нечеткий поиск ....
Расширенный раскрывающийся список: Быстрое создание раскрывающегося списка   |  Зависимый раскрывающийся список   |  Выпадающий список с множественным выбором ....
Менеджер столбцов: Добавить определенное количество столбцов  |  Переместить столбцы  |  Переключить статус видимости скрытых столбцов  |  Сравнить диапазоны и столбцы ...
Рекомендуемые функции: Сетка Фокус   |  Просмотр дизайна   |   Большой Формулный Бар    Менеджер книг и листов   |  Библиотека ресурсов (Авто текст)   |  Выбор даты   |  Комбинировать листы   |  Шифровать/дешифровать ячейки    Отправлять электронные письма по списку   |  Суперфильтр   |   Специальный фильтр (фильтровать жирным шрифтом/курсивом/зачеркиванием...) ...
15 лучших наборов инструментов12 Текст Tools (Добавить текст, Удалить символы, ...)   |   50+ График Тип (Диаграмма Ганта, ...)   |   40+ Практических Формулы (Рассчитать возраст по дню рождения, ...)   |   19 Вносимые Tools (Вставить QR-код, Вставить изображение из пути, ...)   |   12 Конверсия Tools (Числа в слова, Конверсия валюты, ...)   |   7 Слияние и разделение Tools (Расширенные ряды комбинирования, Разделить клетки, ...)   |   ... и более

Усовершенствуйте свои навыки работы с Excel с помощью Kutools for Excelи испытайте эффективность, как никогда раньше. Kutools for Excel Предлагает более 300 расширенных функций для повышения производительности и экономии времени.  Нажмите здесь, чтобы получить функцию, которая вам нужна больше всего...

вкладка kte 201905


Office Tab Добавляет в Office интерфейс с вкладками и значительно упрощает вашу работу

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!
Comments (55)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
How do I automatically protect a row based on a cell?
Example: if you enter a value in cell E1, it will automatically protect the cells to the left of the row, D1, C1, B1 and A1
And the same would apply to the following lines, if you enter a value in cell E2 it will automatically protect the cells to the left and so on.

Please help me.
This comment was minimized by the moderator on the site
I need an automatic command that whenever I put something in cell g3, g4, g5 .... it automatically protects the data in the cells on the left ...
example: if you insert data in cell g3, it will automatically protect cells F3, E3, D3, C3, B3, A3... could you help me?


Today I can only save this way by creating a button, and it is very manual and time-consuming...
This comment was minimized by the moderator on the site
there is this command that protects an entire line, but I can't think of anything to solve my case and automate the protection

If Target.Row = 1 And Target.Value <> "" Then
This comment was minimized by the moderator on the site
Hello, Is there any way to have this repeat down an entire sheet. I have this code entered:
Private Sub Worksheet_Change(ByVal Target As Range)
If Range("X3") = "N0" Then
Range("B3:W3").Locked = False
ElseIf Range("X3") = "Yes" Then
Range("B3:W3").Locked = True
End If
End Sub

This is working fine for that row but I would like it to apply to each row as the value "Yes" is selected in column X. Is this possible and if so how do I do that? 
Thanks! 

This comment was minimized by the moderator on the site
Hi Stephanie,
Do you mean that when Yes is selected in each cell of column X, the corresponding row will be locked? When switching to No, the corresponding row will be unlocked?Or just select Yes in any cell of column X to lock all rows in the current worksheet?
This comment was minimized by the moderator on the site
I want to allow only 2 cells to edit as L after the two edits remaining cells should lock in that column can it possible ?
This comment was minimized by the moderator on the site
Hi Venkat,You can see if there is an answer you need in this article.
https://www.extendoffice.com/documents/excel/3778-excel-lock-cell-after-data-entry-input.html
This comment was minimized by the moderator on the site
I'm using this fine to lock Cells B-D when the value in A is entered. I need this to be replicated for almost 500 rows in 8 sheets. is there a way to do this without having to type 400 lines on code? i.e. if the value in a = "accepted" then columns b-D are locked for that row only
This comment was minimized by the moderator on the site
The code does not do anything when I tried it. Does this work on MS Office Professional 2010?
Thanks.
This comment was minimized by the moderator on the site
Hi Maz,The code has been successfully tested in Excel 2010.
This comment was minimized by the moderator on the site
If my first column has strings can I lock that row specifically to the first column, where when I do a sort the full row will stay together on the sort?
This comment was minimized by the moderator on the site
Good day,Sorry can't help you for that.
This comment was minimized by the moderator on the site
Hello,

I need your favour. when i select No option from a cell i want the columns below to be locked/greyed out.

Is that possible? I tried this formula but dint work

Private Sub Worksheet_Change(ByVal Target As Range)

If Range("D90") = "Yes" Then

Range("C94:F104").Locked = False

ElseIf Range("D90") = "No" Then

Range("C94:F104").Locked = True

End If

End Sub
This comment was minimized by the moderator on the site
Hi Steffi,
The code works well.
If you want to lock the range of cells to prevent editing, you need to protect the worksheet manually after selecting No option in D90.
And as D90 is in the range C94:F104, after protecting the worksheet, D90 can't be edited either.
This comment was minimized by the moderator on the site
D90 is not in the range. It's 4 rows above C94
This comment was minimized by the moderator on the site
I copied everything from above into a sheet. It worked for a second and now I'm getting the error 'Unable to set the Locked property of the Range class'. I even opened a whole new sheet and copied your example verbatim. Any idea whats going on?
This comment was minimized by the moderator on the site
Hi please any one help me for VBA code .

if i select from drop down in cell Range(A1:A1000) "abc" then not lock Range(D1:D1000) to (F1:F1000)



if i select from drop down in cell Range(A1:A1000) "abc" then not lock Range(D1:D1000) to (F1:F1000)



if i select from drop down in cell Range(A1:A1000) "abc" then lock Range(D1:D1000) to (F1:F1000)



i.e respective cell A1 for D1 to F1



A2 for for D2 to F2
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations