【问题标题】:Add timestamp in excel worksheet if row has changed如果行已更改,则在 Excel 工作表中添加时间戳
【发布时间】:2014-04-28 23:49:10
【问题描述】:

如果行已更改,我需要在 Excel 工作簿中添加或更新时间戳。我正在进行数据导入,但我需要查看更新/添加的行以及日期。

到目前为止,我已经找到并调整了以下代码:

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    With Target
        If .Count > 1 Then Exit Sub
        If Not Intersect(Range("A2:BL9999"), .Cells) Is Nothing Then
            Application.EnableEvents = False
            With .Cells(1, 65)
                 .NumberFormat = "yyyy.mm.dd"
                 .Value = Now
            End With
            Application.EnableEvents = True
        End If
    End With
End Sub

问题是,时间戳总是相对于已进行更改的行 + 65 行添加,而不是在列 BM(索引 65)中。

您能告诉我,我应该使用或更改哪个功能?

【问题讨论】:

  • With .Cells(1, 65)更改为With Cells(1, 65)
  • 在这种情况下它根本没有更新
  • 代码更新BM1单元格
  • 也许我做错了什么,但没有发生任何更改,我什至尝试复制新的 excel 文件并将范围和单元格设置为 10,如果进行了这些更改,则工作表中没有更新完全没有
  • 按预期为我工作。单元格BM1 包含时间戳。顺便说一句,代码只有在 A2:BL9999 范围内更改 single 单元格时才有效

标签: excel timestamp vba


【解决方案1】:

以及对列BM 的修复更好

  1. 处理所有可能已更改的行,而不是退出并保留任何记录
  2. 关闭ScreenUpdating 以提高速度

代码

Private Sub Worksheet_Change(ByVal Target As Range)
Dim rng1 As Range
Dim rng2 As Range

Set rng1 = Intersect(Target, Range("A2:BL9999"))
If rng1 Is Nothing Then Exit Sub

With Application
    .ScreenUpdating = False
    .EnableEvents = False
End With

For Each rng2 In rng1.Cells
    With Cells(rng2.Row, 65)
          .NumberFormat = "yyyy.mm.dd"
           .Value = Now
    End With
Next

With Application
    .ScreenUpdating = True
    .EnableEvents = True
End With

End Sub

【讨论】:

    【解决方案2】:

    要更改相对于整行的引用,请使用.EntireRow

    所以那行应该是:With .EntireRow.Cells(1, 65)

    请注意,即使在处理单行时,您仍然可以使用 A1 样式引用。这可以使您不必计算列。例如,在这种情况下,.EntireRow.Range("BM1").EntireRow.Cells(1, 65) 的含义完全相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      • 1970-01-01
      • 2011-01-10
      • 1970-01-01
      • 2020-11-25
      • 1970-01-01
      相关资源
      最近更新 更多