Excel运行VBA代码然后崩溃

时间:2014-03-30 13:16:40

标签: excel vba excel-vba timestamp

我已经在2010年以前的各种版本的Excel中使用这个简单的代码多年了,这是通过在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

2 个答案:

答案 0 :(得分: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. 避免重新入境

答案 1 :(得分:0)

另一种更短的版本是

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列中输入多个值时也适用。

相关问题