【问题标题】:How to set a timestamp when value of a cell containing a formula updates the first time?当包含公式的单元格的值第一次更新时如何设置时间戳?
【发布时间】:2020-04-07 04:06:03
【问题描述】:

我有一个包含三个工作表的工作簿。

Worksheet1 包含 worksheet2 和 worksheet3 的汇总。 Worksheet1 永远不会手动更新,因为数据/信息在 worksheet2/3 中更新,并通过单元格中的 vlookup 公式填充到 worksheet1。

每当工作表 1 的 D 列中的单元格首先包含 1%-99% 的百分比时,我想要一个时间戳。

  • 我希望这个时间戳在输入第一个数据后永远不会改变。
  • 我还希望时间戳显示在 G 列中。

每当工作表 1 中 D 列中的单元格首先包含 100% 时,我想要另一个时间戳。

  • 我希望这个时间戳在输入第一个数据后永远不会改变。
  • 我还希望在 H 列中打印时间戳。

只有在手动更改单元格时才会出现这种情况。由于工作表是根据公式填充的,因此没有发现变化。

Private Sub Worksheet_Change(ByVal Target As Range)

Dim myTableRange As Range
Dim myDateTimeRage As Range
Dim myUpdatedRange As Range

Set myTableRange = Range("D1:D314")

If Intersect(Target, myTableRange) Is Nothing Then Exit Sub

Set myDateTimeRage = Range("N" & Target.Row)
Set myUpdatedRange = Range("O" & Target.Row)

If myDateTimeRage.Value = "" Then
    myDateTimeRage.Value = Now
End If

myUpdatedRange.Value = Now

End Sub

【问题讨论】:

  • 如果你在处理公式,你需要使用Worksheet_Calculate,而不是Worksheet_Change
  • 您必须在工作表 2+3 中寻找变化;如果他们更改,请查看工作表 1,如果单元格包含您要查找的内容,然后设置时间戳。
  • 如果我使用 worksheet_calculate 代码不起作用
  • 您是要在columns G and H 中为您的文本添加时间戳,还是在Columns N and O 中为您的代码添加时间戳?

标签: excel vba excel-formula timestamp worksheet


【解决方案1】:

这是与Worksheet_Calculate一起使用的基本代码

Private Sub Worksheet_Calculate()
Dim myTableRange As Range

Set myTableRange = Range("D1:D30") 'Change the range as needed

    For Each cel In myTableRange 
    'when a cell is changed in the range due to a formula, the code loops through and checks all the cells for a change. 

        If cel.Value >= 0.01 And cel.Value <= 0.99 And cel.Offset(, 3).Value = "" And cel.Offset(, 4).Value = "" Then 
       'If the timestamp is not for columns G and H, change the offset(,3) to 10, and offset(,4) to 11

            cel.Offset(, 3).Value = Now

        ElseIf cel.Value = 1# And cel.Offset(, 4).Value = "" Then
        'Test for 100%

            cel.Offset(, 4).Value = Now
        End If

    Next cel
End Sub

【讨论】:

  • 这段代码效果很好!我想添加一条语句,首先在 G 和 H 列中检查现有数据。如果从前一天开始存在现有日期,则代码已运行并带有时间戳,我不希望上面的代码运行并覆盖这些现有日期。是否可以将此代码嵌套到另一个 else if 语句中?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多