Ir para o conteúdo principal

Como limpar o conteúdo da célula especificada se o valor de outra célula for alterado no Excel?

Suponha que você queira limpar um intervalo de conteúdo de célula especificado se o valor de outra célula for alterado, como você pode fazer? Esta postagem vai mostrar um método para resolver esse problema.

Limpe o conteúdo da célula especificada se o valor de outra célula mudar com o código VBA


Limpe o conteúdo da célula especificada se o valor de outra célula mudar com o código VBA

Como mostrado na captura de tela abaixo, quando o valor na célula A2 é alterado, o conteúdo na célula C1: C3 será apagado automaticamente. Faça o seguinte.

1. Na planilha, você limpará o conteúdo da célula com base nas alterações de outra célula, clique com o botão direito na guia da planilha e selecione Ver código no menu de contexto. Veja a imagem:

2. Na abertura Microsoft Visual Basic para Aplicações janela, copie e cole abaixo do código VBA na janela de código.

Código VBA: Limpe o conteúdo da célula especificada se o valor de outra célula mudar

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

Note: No código, B2 é a célula na qual você limpará o conteúdo da célula e C1: C3 é o intervalo do qual você limpará o conteúdo. Altere-os conforme necessário.

3. aperte o outro + Q chaves para fechar o Microsoft Visual Basic para Aplicações janela.

Então você pode ver o conteúdo no intervalo C1: C3 é apagado automaticamente quando o valor na célula A2 muda conforme a captura de tela abaixo mostrada.


Artigos relacionados:

Melhores ferramentas de produtividade de escritório

🤖 Assistente de IA do Kutools: Revolucionar a análise de dados com base em: Execução Inteligente   |  Gerar Código  |  Crie fórmulas personalizadas  |  Analise dados e gere gráficos  |  Invocar funções do Kutools...
Recursos mais comuns: Encontre, destaque ou identifique duplicatas   |  Excluir linhas em branco   |  Combine colunas ou células sem perder dados   |   Rodada sem Fórmula ...
Super pesquisa: VLookup de múltiplos critérios    VLookup de múltiplos valores  |   VLookup em várias planilhas   |   Pesquisa Difusa ....
Lista suspensa avançada: Crie rapidamente uma lista suspensa   |  Lista suspensa de dependentes   |  Lista suspensa de seleção múltipla ....
Gerenciador de colunas: Adicione um número específico de colunas  |  Mover colunas  |  Alternar status de visibilidade de colunas ocultas  |  Compare intervalos e colunas ...
Recursos em destaque: Foco da Grade   |  Vista de Design   |   Grande Barra de Fórmula    Gerenciador de pastas de trabalho e planilhas   |  Biblioteca (Auto texto)   |  Data Picker   |  Combinar planilhas   |  Criptografar/Descriptografar Células    Enviar e-mails por lista   |  Super Filtro   |   Filtro Especial (filtro negrito/itálico/tachado...) ...
15 principais conjuntos de ferramentas12 Texto Ferramentas (Adicionar texto, Remover Personagens, ...)   |   50+ de cores Tipos (Gráfico de Gantt, ...)   |   Mais de 40 práticos Fórmulas (Calcule a idade com base no aniversário, ...)   |   19 Inclusão Ferramentas (Insira o código QR, Inserir imagem do caminho, ...)   |   12 Conversão Ferramentas (Números para Palavras, Conversão de moedas, ...)   |   7 Unir e dividir Ferramentas (Combinar linhas avançadas, Dividir células, ...)   |   ... e mais

Aprimore suas habilidades de Excel com o Kutools para Excel e experimente uma eficiência como nunca antes. Kutools para Excel oferece mais de 300 recursos avançados para aumentar a produtividade e economizar tempo.  Clique aqui para obter o recurso que você mais precisa...

Descrição


Office Tab traz interface com guias para o Office e torna seu trabalho muito mais fácil

  • Habilite a edição e leitura com guias em Word, Excel, PowerPoint, Publisher, Access, Visio e Project.
  • Abra e crie vários documentos em novas guias da mesma janela, em vez de em novas janelas.
  • Aumenta sua produtividade em 50% e reduz centenas de cliques do mouse para você todos os dias!
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