繁体   English   中英

如果另一个更改为空白,则清除单元格的内容

[英]Clear contents of cell if another changes to blank

我有一个 Excel 工作表,如果在 A 列的单元格中输入一个值,那么 B 列中它旁边的单元格会自动生成日期和时间。 我遇到的问题是我想要检查 A 列中的值是否为空,即“”,那么日期和时间也被清除。 我已经弄清楚如何添加日期和时间,而不是如何添加对单元格值的检查以查看它是否为空白。 代码如下,并附有示例;

例子;

A4 a change is made, the current date and time is entered into B4 
A8 a change is made, the current date and time is entered into B8
A4 the user clears the cell (presses delete on their keyboard), B4 is cleared too.
A4 the user enters "hello world", the current date and time is entered again

代码;

Private Sub Worksheet_Change(ByVal Target As Range)
Dim xCellColumn As Integer
Dim xTimeColumn As Integer
Dim xRow, xCol As Integer
xCellColumn = 2
xTimeColumn = 5
xRow = Target.Row
xCol = Target.Column
If Target.Text <> "" Then
    If xCol = xCellColumn Then
       Cells(xRow, xTimeColumn) = Now()
    End If
End If
End Sub

谢谢

这仅适用于A列和B列:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Cells.Count > 1 Then Exit Sub
    If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub

    Application.EnableEvents = False
    If Target = vbNullString Then
        Target.Offset(0, 1) = vbNullString
    Else
        Target.Offset(0, 1) = Now
    End If

    Application.EnableEvents = True

End Sub

如果要使其适用于任何 2 列,请删除此行:

If Intersect(Target, Range("A:A")) Is Nothing Then Exit Sub

命令Application.EnableEvents = True用于确保一旦Sub更改单元格就不会调用_Change事件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM