将Workbook_SheetChange应用于一个工作表

我发现下面的代码,我正在尝试适应,但它似乎运行在我的工作簿中的每个工作表,我只希望它适用于“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 ' eg, 1 = 00:01 AM TimeStr = "00:0" & .Value Case 2 ' eg, 12 = 00:12 AM TimeStr = "00:" & .Value Case 3 ' eg, 735 = 7:35 AM TimeStr = Left(.Value, 1) & ":" & _ Right(.Value, 2) Case 4 ' eg, 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 

我哪里错了?

您已将Workbook_SheetChange事件macros与单个Worksheet_Change事件macros混淆。

您可以通过将代码包装在这样的东西中来隔离现有的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