You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

仅在非空单元格变更时生成VBA时间戳及代码优化问询

Excel VBA 代码优化问题

我查过不少相关帖子,但没找到完全匹配需求的方案。目前使用的VBA代码可实现功能,但存在两个问题:

  • 仅需在单元格非空时检测变更。当前单元格录入数据时,即便因限制未更新时间戳,操作仍极慢,每次输入需间隔1-2秒。
  • 当前通过逐个列号排除的方式处理列过滤,是否有更优实现方式?

需求补充

单元格为空时录入新订单信息,不更新用户名和时间戳;后续非排除列的信息变更时,更新对应行的用户名和时间戳为Now()。

当前使用的VBA代码

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
 

    Dim ThisRow As Long
    ThisRow = Target.Row

    'protect Header row from any changes
    If (ThisRow = 1) Then

           Application.EnableEvents = False
           Application.Undo
           Application.EnableEvents = True
           MsgBox "Header Row is Protected."
           Exit Sub

    End If

    If Target.Column >= 1 And Target.Column <> 7 And Target.Column <> 20 And Target.Column <> 24 And Target.Column <> 26 And Target.Column <> 28 And Target.Column <> 29 And Target.Column <> 30 Then

        Dim sOld As String, sNew As String
        sNew = Target.Value 'Log the new value

        With Application
            .EnableEvents = False
            .Undo
        End With

        sOld = Target.Value 'Log the old value
        Target.Value = sNew 'reset new value

        If sOld <> sNew Then

            ' time stamp corresponding to cell's last update
            Range("AD" & ThisRow).Value = Now
            ' Choose between Windows level UserName or Application level UserName
            'Range("AB" & ThisRow).Value = Environ("username")
            Range("AB" & ThisRow).Value = Application.UserName
            Range("AB:AD").EntireColumn.AutoFit

        End If
         

        Application.EnableEvents = True

    End If
    'Set timestamps based on status dropdown
   Dim G As Range: Set G = Range("G2:G5000")
   Dim v As String
   If Intersect(Target, G) Is Nothing Then Exit Sub

   Application.EnableEvents = False
      v = Target.Value
      If v = "ARB" Then Target.Offset(0, 29) = Now()
      If v = "VGA" Then Target.Offset(0, 30) = Now()
   Application.EnableEvents = True
    
End Sub

内容的提问来源于stack exchange,提问作者Tony Montez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 02:35:39