excel - 使用 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 中更改任何内容,是否可以清除整行?
谢谢!
解决方案
假设您不想清除标题行
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
推荐阅读
- python - 2.4版本的Tensorflow,pip安装tensorflow后是否要单独做tensorflow-gpu?
- arrays - 使用 Python 从 txt 文件中读取二维数组
- html - 来自 w3schools.com 的示例代码的奇怪 IE 行为
- ruby-on-rails - React Native 忽略 JWT 身份验证 Rails API
- python - Tensorflow model.fit() 打印没有错误的重复消息
- windows - Windows 10 通过 acript 创建热键
- git - AWSCodeCommit 和多个使用 GIT 的用户
- javers - Javers 中具有多个 Id 属性的 EntityDefinition 的 Id 生成顺序是什么
- twilio - 如果可以在 twilio 中看到 api 日志
- javascript - d3 示例中未定义路径