【问题标题】:Clear contents of cell if another changes to blank如果另一个更改为空白,则清除单元格的内容
【发布时间】:2018-06-22 08:56:33
【问题描述】:

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

谢谢

【问题讨论】:

    标签: excel vba formula


    【解决方案1】:

    这仅适用于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 事件。

    【讨论】:

      猜你喜欢
      • 2020-02-17
      • 1970-01-01
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      相关资源
      最近更新 更多