首页 > 解决方案 > 当另一个单元格为空白时,自动清除一个单元格的内容

问题描述

我想基于另一个单元格为空白的单元格自动清除内容。
在此处输入图像描述

我在 L 列的“跟踪器”表中有值,它们依赖于 AF 列中另一表(“公式”)中完全相同的行。

例如,当我从单元格 L2 中手动删除值时,我想自动清除列 AF2 的内容等。

如果值小于另一个单元格值,我发现清除 Excel 单元格
我尝试了以下操作:

Sub ClearLowerThan()
Dim c As Range, Rng As Range
Dim LastRow As Long
Dim ws As Worksheet, ws2 As Worksheet: Set ws = Sheets("Tracker")
Set ws2 = Sheets("Formulas")
'declare you worksheet, amend as required
LastRow = ws.Cells(ws.Rows.Count, "L").End(xlUp).Row

CompareVal = LastRow

'get the value to compare against, in this case from cell B1

Set Rng = ws2.Range("AF2:AF" & LastRow)
'set the range to compare against the value from B1

For Each c In Rng 'for each cell in the given range
    If c.value < CompareVal Then c.ClearContents
    'if value of cell is less than the value to compare against, clear the cell contents.
Next
End Sub

我没有看到任何反应。我知道,该代码指的是清除低于的数据,但我不知道如何为我的目的更改它。

Excel 中:如何使用 VBA 检查单元格是否为空?我找到了这个IsEmpty()功能。我变了

  If c.value < CompareVal Then c.ClearContents

  If IsEmpty(CompareVal.value) Then c.ClearContents

我收到一个错误:调试器指向此行时需要对象。

如何自动删除位于同一行的另一张工作表中单元格的值?

标签: excelvba

解决方案


请复制Tracker模块表中的下一个代码:

Option Explicit


Private Sub Worksheet_Change(ByVal Target As Range)
 If Not Target.Column = 12 Then Exit Sub 'it does work only for changes in column L:L
 Dim ws2 As Worksheet: Set ws2 = Sheets("Formulas")

 ws2.Range("AF" & Target.row).Value = Target.Value
End Sub

推荐阅读