2014-03-30 207 views
0

我一直使用这个简单的代码多年来在各种版本的Excel直到2010年,这是时间戳记在一张表上的项目,通过在列A中输入一个数字的入境时间将插入列B中的相邻单元格中。 我最近购买了平板电脑,因为这样可以为电子表格提供更好的使用方式。该平板电脑运行的是Windows 8和Office 2013.当我运行工作表时,时间输入到单元格中,但之后立即发出“Microsoft Excel已停止工作”的消息,Excel关闭。 我已经在平板电脑上加载Excel 2010,因为我认为问题可能是Excel 2013,但这也不起作用。Excel运行VBA代码,然后崩溃

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 

回答

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. 避免重新进入
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列中输入多个值时也有效。