首页 > 解决方案 > 使用 VBA 根据对动态下拉列表的更新来清除内容

问题描述

我正在尝试根据使用 VBA 对另一个单元格的更新来清除单元格的内容。

E 到 H 列都是动态下拉列表。我有以下代码:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("D2")) Is Nothing Then
        Range("E2:H2").ClearContents
    End If
End Sub

这适用于第 2 行,但我如何将其设为一个范围,以便如果我更改 D3,它将清除所有行的 E3:H3 等等。另外,如果我在 D 到 H 中更改任何内容,是否可以清除整行?

谢谢!

标签: excelvba

解决方案


假设您不想清除标题行

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Row = 1 then exit sub

    ' This will clear the row if something is changed in Column D:
    If Not Intersect(Target, Range("D:D")) Is Nothing Then
        Range(Cells(Target.Row, "E"), Cells(Target.Row, "H")).ClearContents
    End If
End Sub

如果要清除整行,可以使用

Target.EntireRow.ClearContents

但是,这会导致 2 个问题:
您还将清除刚刚输入的信息(因为它是行的一部分)。您可以通过保存数据来防止这种情况:

Dim backup As Variant
backup = Target.value
Target.EntireRow.ClearContents
Target.value = backup

第二个问题是使用 VBA 在单元格中写入内容将再次触发Change-Trigger(依此类推,最终导致 Stack Overflow 运行时错误)。为避免这种情况,您需要在触发代码运行时禁用事件 - 最后不要忘记启用它们。

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error Goto Change_Exit  ' To ensure that events are reactivated in any case
    Application.EnableEvents = False
    (do your stuff here)

Change_Exit: 
    Application.EnableEvents = True
End Sub

更新:要仅清除右侧的字段,请使用

If Not Intersect(Target, Range("D:G")) Is Nothing Then
    Range(Target.Offset(0, 1), Cells(Target.Row, "H")).ClearContents
End If

推荐阅读