将Workbook_SheetChange应用于一个工作表

时间:2015-11-09 08:38:56

标签: excel vba excel-vba

我发现下面的代码我试图适应,但它似乎在我的工作簿中的每个工作表上运行,我只希望它适用于" Sheet3"。我已经尝试将其粘贴到Sheet3代码模块中,但这似乎不起作用。

Private Sub Workbook_SheetChange(ByVal Sh As Object, _
  ByVal Target As Excel.Range)
    Dim TimeStr As String

    On Error GoTo EndMacro
    If Application.Intersect(Target, Range("A1:a15")) Is Nothing Then
        Exit Sub
    End If
    If Target.Cells.Count > 1 Then
        Exit Sub
    End If
    If Target.Value = "" Then
        Exit Sub
    End If

    Application.EnableEvents = False
    With Target
        If .HasFormula = False Then
            Select Case Len(.Value)
                Case 1 ' e.g., 1 = 00:01 AM
                    TimeStr = "00:0" & .Value
                Case 2 ' e.g., 12 = 00:12 AM
                    TimeStr = "00:" & .Value
                Case 3 ' e.g., 735 = 7:35 AM
                    TimeStr = Left(.Value, 1) & ":" & _
                    Right(.Value, 2)
                Case 4 ' e.g., 1234 = 12:34
                    TimeStr = Left(.Value, 2) & ":" & _
                    Right(.Value, 2)
                Case Else
                    Err.Raise 0
            End Select
            .Value = Format(TimeValue(TimeStr), "hh:mm")
        End If
    End With
    Application.EnableEvents = True

    Exit Sub

EndMacro:
    MsgBox "You did not enter a valid time"
    Application.EnableEvents = True
    ActiveCell.Offset(-1, 0).Select
End Sub

我哪里错了?

1 个答案:

答案 0 :(得分:1)

您已将Workbook_SheetChange事件宏与各个Worksheet_Change事件宏混淆。

您可以通过将代码包装在这样的内容中来隔离现有的Workbook_SheetChange。

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Excel.Range)
    If sh.Name = "Sheet3" Then
        'all of the rest of the code
    End If
End Sub

或者,将代码放入 Sheet3 工作表代码页并将子代码更改为此。

Private Sub Worksheet_Change(ByVal Target As Range)
    'all of the rest of the code
End Sub