2014-03-30 130 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列中輸入多個值時也有效。