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

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

Предположим, вы хотите очистить диапазон указанного содержимого ячейки, если значение другой ячейки изменилось, как вы можете это сделать? Этот пост покажет вам способ решения этой проблемы.

Очистить указанное содержимое ячейки, если значение другой ячейки изменяется с кодом VBA


Очистить указанное содержимое ячейки, если значение другой ячейки изменяется с кодом VBA

Как показано ниже, при изменении значения в ячейке A2 содержимое ячейки C1: C3 будет очищено автоматически. Пожалуйста, сделайте следующее.

1. На рабочем листе вы очистите содержимое ячейки на основе изменений другой ячейки, щелкните правой кнопкой мыши вкладку листа и выберите Просмотреть код из контекстного меню. Смотрите скриншот:

2. В дебюте Microsoft Visual Basic для приложений окна, скопируйте и вставьте под кодом VBA в окно кода.

Код VBA: очистить указанное содержимое ячейки при изменении значения другой ячейки

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("A2")) Is Nothing Then
        Range("C1:C3").ClearContents
    End If
End Sub

Внимание: В коде B2 - это ячейка, на основе которой вы очищаете содержимое ячейки, а C1: C3 - это диапазон, из которого вы очищаете содержимое. Пожалуйста, измените их по своему усмотрению.

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

Затем вы можете увидеть содержимое диапазона C1: C3 очищается автоматически при изменении значения в ячейке A2, как показано ниже.


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

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

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

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

Описание


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

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!
Comments (38)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Hallo,

Dankeschön für die Hilfe.


LG Stefan
This comment was minimized by the moderator on the site
Hallo,
ich möchte das Makro bitte so erweitern, wenn ich in B2 klicke, das nur C2 gelöscht wird, wenn ich in B3 klicke dann soll nur C3 gelöscht werden usw. bis B100 dann soll nur C100 gelöscht werden.
Und das soll auch wechelseitig funktionieren.
Wenn ich in C2 klicke dann soll nur B2 gelöscht werden usw.

Vielen Dank im Vorraus

LG Stefan




Private Sub Worksheet_Change(ByVal Target As Range)
'Updated by Extendoffice 20220721
If Target.Cells.Count > 1 Then Exit Sub
If (Not Intersect(Target, Range("B2")) Is Nothing) And (Target.Value = "Yes") Then
Range("B3").ClearContents
Else
If (Not Intersect(Target, Range("B3")) Is Nothing) And (Target.Value = "Yes") Then
Range("B2").ClearContents
End If
End If
End Sub
This comment was minimized by the moderator on the site
Hi Stefan,

The following VBA can acheive: when the value of column A is changed, the corresponding cell in column C of the same row will be cleared.
Private Sub Worksheet_Change(ByVal Target As Range)
'Updated by Extendoffice 20221013
    Dim xRight As Range
    Dim KeyCells As Range
    Set KeyCells = Range("A:A")
    Set xRight = Target.Offset(0, 3)
    If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
        xRight.ClearContents
    End If
End Sub
This comment was minimized by the moderator on the site
Hola, estoy trabajando una base de datos en OFFICE ONLINE a traves de ONEDRIVE, quiero que al PONER "CANCELADO" o "NOSHOW" elimine el contenido de la fila seleccionada.
This comment was minimized by the moderator on the site
Hi Angel,
The VBA code does not work in Office Online. Sorry for the inconvenience.
This comment was minimized by the moderator on the site
Hello,
The code below works as advertised but, the following problems occurs:

Firstly, when resizing the targeted table, all the table data is cleared AND, all but column 1 headers are re-labelled to "Column1, Column2, etc. AND the workbook autosave itslef and kills the undo.

Secondly, when deleting any table row, I get a "Run-time error 1004 (Method Offset of object Range failed.


Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("F3:F500")) Is Nothing Then
     Target.Offset(0, 1).ClearContents
    ElseIf Not Intersect(Target, Range("G3:G500")) Is Nothing Then
        Target.Offset(0, 1).ClearContents
        Target.Offset(0, 2).ClearContents
    ElseIf Not Intersect(Target, Range("H3:H500")) Is Nothing Then
        Target.Offset(0, 1).ClearContents
    End If
End Sub


Any idea of what could be wrong?

Thanks in advance!
This comment was minimized by the moderator on the site
Hallo,

Zu Punkt 3.
Die Taste "Andere" Finde ich nicht auf meiner Windows Tastatur. Ich Habe Strg, Alt, Tab... allerdings die Taste Andere gibt es auf meiner Tastatur leider nicht.

Lieben Gruß Mathias
This comment was minimized by the moderator on the site
Hi Mathias,
If you can't find the corresponding key on the keyboard. You can just click the Save button in the Microsoft Visual Basic Applications window to save the code and then manually close this window.
This comment was minimized by the moderator on the site
Помогите с решением, VBA не знаю. Мне нужно при изменении ячейки удалить данные из другой и чтобы это дейстовало на весь столбец.
Меняю А2 удаляется из G2, меняю А3 удаляется из G3, меняю A6 удаляется из G6 и т.д.

Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A2")) Is Nothing Then
Range("G2").ClearContents
End If
End Sub


Данный код хорош для одной ячейки, а как его размножить на все ячейки столбца?
This comment was minimized by the moderator on the site
Hi Наталья,
The following VBA code can help you solve the problem. Please give it a try.

Private Sub Worksheet_Change(ByVal Target As Range)
'Updated by Extendoffice 20221013
    Dim xRight As Range
    Dim KeyCells As Range
    Set KeyCells = Range("A:A")
    Set xRight = Target.Offset(0, 6)
    If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
        xRight.ClearContents
    End If
End Sub
This comment was minimized by the moderator on the site
Buongiorno, avrei bisogno di cancellare una serie di caselle (un rettangolo, quindi su più righe e colonne) in base al valore di un'altra cella. es: se la cella A2 è inferiore di 12, il quadrato con vertici opposto C2 : F4 venga cancellato.
Grazie mille
This comment was minimized by the moderator on the site
Hi Pietro,
Sorry I don't quite understand your question. Do you mind uploading a screenshot of your data?
This comment was minimized by the moderator on the site
Hello,

Just looking for an easy way to make it so if "B2" has selected "Yes" from the data validation list, cell B3 would clear it's data... and vice-versa: If "B3" has selected "Yes" from the data validation list, cell "B2" would clear it's data.

Basically B2 or B3 can say "Yes" (from the data validation list) but never at the same time, one should clear the other.
This comment was minimized by the moderator on the site
Hi Jeff,
The following VBA code can do you a favor. Please give it a try.
Private Sub Worksheet_Change(ByVal Target As Range)
'Updated by Extendoffice 20220721
If Target.Cells.Count > 1 Then Exit Sub
    If (Not Intersect(Target, Range("B2")) Is Nothing) And (Target.Value = "Yes") Then
        Range("B3").ClearContents
        Else
        If (Not Intersect(Target, Range("B3")) Is Nothing) And (Target.Value = "Yes") Then
        Range("B2").ClearContents
    End If
    End If
End Sub
This comment was minimized by the moderator on the site
Bonjour tout le monde,

Besoin d'aide, j'ai besoin d'effacer le contenu d'une cellule de la colonne "I" si la cellule (de la même ligne) de la colonne "O" =0, sur environ 2000 lignes avec des titres tout le 10 lignes environ.
This comment was minimized by the moderator on the site
Is it possible to clear specified cell contents if the trigger cell contains a specific number? Say, IF cell A1 = 1, then clear Cells A2:A4?
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