【问题标题】:How to clear contents of other cells if I delete the main data of which the other cells depend on?如果我删除了其他单元格所依赖的主要数据,如何清除其他单元格的内容?
【发布时间】:2016-09-28 06:24:49
【问题描述】:

我的工作表现在有以下代码。当我在 E 列中输入数据时,返回值(例如注释“new”的日期)将分别在 B、D 和 F 列中正常工作。

但是,当我删除 E 列上的数据时,B、D 和 F 列的返回值仍然存在。

如果我删除了在 E 列中输入的数据,如何清除它们?

非常感谢!

Private Sub Worksheet_Change(ByVal Target As Range)

Dim i As Integer
For i = 2 To 10000
    If Cells(i, "E").Value <> "" And Cells(i, "B").Value = "" Then
        Cells(i, "B").Value = Date
        Cells(i, "B").NumberFormat = "dd.mm.yyyy"
        Cells(i, "D").Value = "NEW"
        Cells(i, "F").Value = "NEW"
    End If

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    如果你的意思是,如果你清除 E 列的内容,然后清除 B、D 和 F 列中的内容,然后使用下面的代码

    (但是,为什么每次单元格更改时都需要扫描整行?)

    Private Sub Worksheet_Change(ByVal Target As Range)
    
    Dim i               As Integer
    
    For i = 2 To 10000
        If Cells(i, "E").Value <> "" And Cells(i, "B").Value = "" Then
            Cells(i, "B").Value = Date
            Cells(i, "B").NumberFormat = "dd.mm.yyyy"
            Cells(i, "D").Value = "NEW"
            Cells(i, "F").Value = "NEW"
        Else
            If Cells(i, "E").Value = "" Then
                Cells(i, "B").ClearContents
                Cells(i, "D").ClearContents
                Cells(i, "F").ClearContents
            End If
        End If
    
    Next i
    
    End Sub
    

    改进的代码:仅在 E 列中的单元格发生更改时运行代码,在这种情况下,仅修改该行的 B、D 和 F 列中的单元格的值。

    Private Sub Worksheet_Change(ByVal Target As Range)
    
    Dim WatchRange                  As Range
    Dim IntersectRange              As Range
    
    ' can modify it to your need, also using dynamic last row with data
    Set WatchRange = Range("E2:E10000")
    Set IntersectRange = Intersect(Target, WatchRange)
    
    ' check values in Column E, only if cells in Column E are modified
    If Not IntersectRange Is Nothing Then
        Dim i               As Integer
    
       ' change value only for relevant row change
        i = Target.Row
    
        If Cells(i, "E").Value <> "" And Cells(i, "B").Value = "" Then
            Cells(i, "B").Value = Date
            Cells(i, "B").NumberFormat = "dd.mm.yyyy"
            Cells(i, "D").Value = "NEW"
            Cells(i, "F").Value = "NEW"
        Else
            If Cells(i, "E").Value = "" Then
                Cells(i, "B").ClearContents
                Cells(i, "D").ClearContents
                Cells(i, "F").ClearContents
            End If
        End If
    
    End If
    
    End Sub
    

    【讨论】:

    • 我已经尝试过上述方法,但是每次我尝试输入新数据时它都会挂起我的程序。谢谢你。 (:
    • 像魅力一样工作!谢谢!
    猜你喜欢
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 2018-07-08
    相关资源
    最近更新 更多