2016-02-17 113 views
0

我有一個功能,把正常時的代碼表爲一個工作表中的Excel工作簿中的以下VBA代碼:轉換Excel的VBA一張工作表到工作簿寬

Private Sub Worksheet_Change(ByVal Target As Range) 

    Application.EnableEvents = False 

    If Not Intersect(Range("E:E"), Target) Is Nothing Then 
     Target = Int(Target) + (Target - Int(Target)) * 100/60 
    End If 

    Application.EnableEvents = True 

End Sub 

我想更改代碼以便我可以將它放在工作簿代碼表中,而不是每個工作表的代碼表中,並且這樣做的結果是我認爲會起作用。但是,它沒有。

Private Sub Workbook_Change(ByVal Sh As Object, ByVal Target As Range) 

    ' Do nothing if not entering data in time cell 
    If (Intersect(Target, Sh.Range("F:F")) Is Nothing) Then Exit Sub 

    Application.EnableEvents = False 

    Dim ws As Worksheet 
    Dim sheets As Variant: sheets = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") 
    Dim sheet As Variant  

    For Each sheet In sheets 
     Set ws = ThisWorkbook.Worksheets(ActiveSheet) 
     If Not Intersect(ws.Range("F:F"), Target) Is Nothing Then 
      Target = Int(Target) + (Target - Int(Target)) * 100/60 
     End If 
     If Int(Target) = 0 Then 
      Target.ClearContents 
     End If 
    Next 

Application.EnableEvents = True 

End Sub 

是否有明顯的錯誤,以便我可以指出正確的方向?

+1

適當的事件是'Private Sub Workbook_SheetChange(ByVal Sh作爲對象,ByVal目標作爲範圍)' –

+1

對於一件事你需要有錯誤處理。否則,如果出現錯誤,最終可能會禁用所有事件。 – RBarryYoung

回答

0

把這個在您的ThisWorkbook代碼:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) 
Dim hr As Boolean 
Dim sheets As Variant: sheets = Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") 
Dim sheet As Variant 
On Error GoTo ext 
For Each sheet In sheets 
    If sheet = Sh.Name Then 
     hr = True 
    End If 
Next sheet 

If Not Intersect(Sh.Range("F:F"), Target) Is Nothing And hr Then 
    Application.EnableEvents = False 
    Target = Int(Target) + (Target - Int(Target)) * 100/60 
    If Int(Target) = 0 Then 
     Target.ClearContents 
    End If 
End If 
Application.EnableEvents = True 
Exit Sub 
ext: 
Application.EnableEvents = True 
End Sub 

我相信這會做你正在嘗試什麼。

編輯:

按照@RBarryYoung,也有人失蹤的錯誤檢查,以確保它重新開啓了活動。

+0

再一次,你釘了我需要的東西。謝謝。 – rkent

+0

@rkent看到編輯我把一個錯誤檢查,以確保事件重新打開。 –

相關問題