将2“Private Sub Worksheet_Change(ByVal Target As Range)”合并为1

我正在创build一个Excel电子表格。 我有两个独立的function,我需要结合,但我不知道如何粉碎它们在一起。 我知道我只能有1个改变事件。 第一个function是解除工作表的保护(c列被locking),当数据input到A列时自动填充C列,或者当A被擦除时擦除C,完成后再次保护。 当数据input到A和B中时,第二行将把单元格焦点返回到下一行A列。单独地,它们根据需要工作。

Private Sub Worksheet_Change(ByVal Target As Range) On Error Resume Next Unprotect Password:="my password" If Target.Column = 1 Then Dim A As Range, B As Range, Inte As Range, r As Range Set A = Range("A:A") Set Inte = Intersect(A, Target) If Target.Offset(0, 1 - Target.Column).Value = "" Then Target.Offset(0, 3 - Target.Column).Clear Exit Sub End If Application.EnableEvents = False For Each r In Inte r.Offset(0, 2).Value = Date & " " & Time r.Offset(0, 2).NumberFormat = "m/d/yyyy h:mm am/pm" Next r Application.EnableEvents = True End If Protect Password:="my password" End Sub Private Sub Worksheet_Change(ByVal Target As Range) On Error GoTo Whoa Application.EnableEvents = False If Not Target.Cells.CountLarge > 1 Then If Not Intersect(Target, Columns(1)) Is Nothing Then Target.Offset(, 1).Select ElseIf Not Intersect(Target, Columns(2)) Is Nothing Then Target.Offset(1, -1).Select End If End If Letscontinue: Application.EnableEvents = True Exit Sub Whoa: MsgBox Err.Description Resume Letscontinue End Sub 

这个怎么样,好像按照你的意思去做,因为我理解这个问题。

 Private Sub Worksheet_Change(ByVal Target As Range) Dim rngIntersect As Range Dim rngCell As Range On Error GoTo TidyUp Application.EnableEvents = False If Target.Column = 1 Then Set rngIntersect = Intersect(Range("A:A"), Target) For Each rngCell In rngIntersect If rngCell.Value = "" Then rngCell.Offset(0, 2).Value = "" Else rngCell.Offset(0, 2).Value = Date & " " & Time rngCell.Offset(0, 2).NumberFormat = "m/d/yyyy h:mm am/pm" End If Next rngCell End If If Target.Column < 3 And Target.Value <> "" Then ' lose the 'And Target.Value <> ""' as desired Cells(Target.Row + Target.Rows.Count, 1).Select End If TidyUp: Set rngIntersect = Nothing Set rngCell = Nothing Application.EnableEvents = True End Sub 

我也build议在你的工作表中使用UserInterfaceOnly.Protect,那么你不必取消保护VBA的工作表。

在模块的两个子过程中实现,然后在事件过程中调用它们。