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

时间:2018-06-22 08:56:33

标签: excel vba formula clear

我有一张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

谢谢

1 个答案:

答案 0 :(得分:2)

这仅适用于列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用于确保_Change更改单元格后不会调用Sub事件。