时间戳变量&静态的

时间:2018-04-23 15:56:41

标签: excel vba excel-vba timestamp

经过一些研究,我发现有很多关于这个主题的信息。但是,我无法弄清楚如何独自解决我的挑战。 我想创建两种时间戳(DATE& TIME)。

  1. 在行BF(BF9:BF)中应该是一个可变时间戳,如果来自A:BE的行中的任何内容被更改,将自动更新,例如,如果A9:BE9中的任何单元格发生变化,则单元格BF9应显示上次更新的日期和时间。

  2. 在行中BG(BG9:BG)应该是一个静态时间戳,它显示第一次在A列中插入任何数据的日期,例如,如果" 12345"于18.04.2018插入细胞A9,然后细胞BG9应永远显示23.04.2018。

  3. 有人知道如何用代码行表达这个吗?不幸的是,我还没有自己解决这个问题。

1 个答案:

答案 0 :(得分:1)

为此,我们可以使用Worksheet_change事件。首先,我们将测试Target更改是否在我们要监控的已定义范围内,如果是,我们会在“更改时间戳”中插入时间戳。该行上的单元格(使用Target中的行)。如果之前没有任何变更,那么“首次变更”将会发生变化。单元格将为空白,因此我们将测试是否为空白,如果是,请插入日期。

评论后更新:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim Seperator As String

    Seperator = ","

    ' Test if change of cell (Target) is in the range specified (A9:BE)
    If Not Intersect(Target, Me.Range("A9:BE" & Me.Rows.Count)) Is Nothing Then
        With Me.Range("A" & Target.Row & ":BE" & Target.Row)
            ' Test if row is empty. I've given two examples here
            ' The first one is simpler but won't identify empty formulas
            ' The second one will compare the values in the range and compare it against a string that would be produced if all the cells were vbNullString
            ' The Join function will only take a 1D array - setting it just to the range will create a 2D array and produce an error so we double transpose
            ' (you could index instead if you want) to get a 1D array

            'If .SpecialCells(xlCellTypeBlanks).Count = .Cells.Count Then
            If Join(Application.Transpose(Application.Transpose(.Value2)), Seperator) = String(.Cells.Count - 1, Seperator) Then
                Me.Range("BF" & Target.Row).ClearContents
                Me.Range("BG" & Target.Row).ClearContents
            Else
                ' If it is insert timestamp in cell BF using row from Target (Cell that was changed)
                Me.Range("BF" & Target.Row).Value2 = Now()
                ' Test if cell BG has anything in it. If not insert date (replicating first change behaviour)
                If Me.Range("BG" & Target.Row).Value2 = vbNullString Then
                    ' Insert date into cell BG using row from Target
                    Me.Range("BG" & Target.Row).Value2 = Date
                End If
            End If
        End With
    End If
End Sub