[英]Converting Excel VBA for a single sheet to workbook wide
我將以下VBA代碼放入Excel工作簿中單個工作表的代碼表中時可以正常運行:
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
是否有明顯的錯誤,以便我可以指向正確的方向?
將其放在您的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,它也丟失了錯誤檢查以確保重新打開事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.