【问题标题】:Excel runs VBA code and then crashesExcel 运行 VBA 代码然后崩溃
【发布时间】:2025-11-23 06:00:02
【问题描述】:

多年来,我一直在各种版本的 Excel 中使用这个简单的代码,直到 2010 年,这是在一张纸上为条目添加时间戳,通过在 A 列中输入一个数字,条目时间将插入到相邻的单元格中B 列。 我最近购买了一台平板电脑,因为它可以更好地使用电子表格。平板电脑正在运行 Windows 8 和 Office 2013。当我运行工作表时,将时间输入到单元格中,但随后立即出现消息“Microsoft Excel 已停止工作”并且 Excel 关闭。 我已经在平板电脑上加载了 Excel 2010,因为我认为问题可能出在 Excel 2013 上,但这也不起作用。

Private Sub Worksheet_Change(ByVal Target As Excel.Range)

Dim c As Integer
Dim f As Integer

c = ActiveCell.Column
r = ActiveCell.Row

If c <> 1 Then End
Cells(r - 1, c + 1) = Time$
Cells(r - 1, c + 1).NumberFormat = "h:mm:ss AM/PM"


End Sub

【问题讨论】:

    标签: vba excel timestamp


    【解决方案1】:
    Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    
    Dim c As Long
    Dim f As Long
    
    c = ActiveCell.Column
    r = ActiveCell.Row
    
    If c <> 1 Then Exit Sub
    If r = 1 Then Exit Sub
    Application.EnableEvents = False
        Cells(r - 1, c + 1) = Now
        Cells(r - 1, c + 1).NumberFormat = "h:mm:ss AM/PM"
    Application.EnableEvents = True
    
    End Sub
    
    1. 更改 DIM 的
    2. 错误测试
    3. 避免再次进入

    【讨论】:

      【解决方案2】:

      另一种较短的版本是

      Private Sub Worksheet_Change(ByVal Target As Excel.Range)
      
          If Not (Intersect(Target, Range("A2", Range("A2").End(xlDown))) Is Nothing) Then
              Application.EnableEvents = False
      
              Target.Offset(0, 1) = Now
              Target.Offset(0, 1).NumberFormat = "h:mm:ss AM/PM"
      
              Application.EnableEvents = True
          End If
      
      End Sub
      

      当在第 1 列中输入多个值时,此解决方案也有效。

      【讨论】: