将单个工作表的Excel VBA转换为工作簿范围

时间:2016-02-17 20:08:19

标签: excel vba excel-vba macros

我有以下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

那里是否有明显的错误,以便我可以指向正确的方向?

1 个答案:

答案 0 :(得分: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,它也错过了错误检查以确保它重新开启事件。