在worksheet_change VBA代码中使用不同的macros调用的多个目标

我想使用worksheet_change()来运行macro1,如果cell1被改变,macro2如果cell2被改变,等等。我知道worksheet_change()只允许target和sh,并且只能使用一个sub。 我以为我可以运行像这样的东西:

Private Sub Targets(ByVal Target As Range) Select Case Target.Address Case "cell1" Call SheetChange.macro1 Case "cell2" Call SheetChange.macro2 Case "cell3" Call SheetChange.macro3 End Select End Sub 

但是,显然我不能! 我也试过了

 Private Sub Targets(ByVal Target As Range) If Target.Address="cell1" Then Call SheetChange.macro1 ElseIf Target.Address="cell2" Then Call SheetChange.macro2 Elseif Target.Address="cell3" Then Call SheetChange.macro3 End If End Sub 

但也没有运气。 任何帮助?

看到这个例子。 你必须使用Intersect来检查一个特定的单元格是否被改变了。 我以A1A2A3为例

我也build议看看这个链接 ,告诉你在使用Worksheet_Change时需要注意什么

 Private Sub Worksheet_Change(ByVal Target As Range) On Error GoTo Whoa Application.EnableEvents = False If Not Intersect(Target, Range("A1")) Is Nothing Then '~~> Run Macro here ElseIf Not Intersect(Target, Range("A2")) Is Nothing Then '~~> Run Macro here ElseIf Not Intersect(Target, Range("A3")) Is Nothing Then '~~> Run Macro here End If Letscontinue: Application.EnableEvents = True Exit Sub Whoa: MsgBox Err.Description Resume Letscontinue End Sub 

您可能还想要处理用户复制和粘贴多个单元格的情况。 在这种情况下,使用此来检查它并采取适当的行动。

  '~~> For Excel 2003 If Target.Count > 1 Then End If '~~> For Excel 2007 + If Target.CountLarge > 1 Then End If 

这是一个方法:

 Private Sub Worksheet_Change(ByVal Target As Range) If Target.Address = "$A$1" Then MsgBox Target.Address Exit Sub End If If Target.Address = "$A$2" Then MsgBox Target.Address Exit Sub End If If Target.Address = "$A$3" Then MsgBox Target.Address Exit Sub End If If Target.Address = "$A$4" Then MsgBox Target.Address Exit Sub End If End Sub 

或者,如果您更喜欢select case语法,则可以使用以下路由:

 Private Sub Worksheet_Change(ByVal Target As Range) Select Case Target.Address Case "$A$1" MsgBox Target.Address Case "$A$2" MsgBox Target.Address Case "$A$3" MsgBox Target.Address Case "$A$4" MsgBox Target.Address End Select End Sub