在worksheet_change VBA代码中具有不同宏调用的多个目标

时间:2013-04-18 16:30:53

标签: excel excel-vba syntax-error worksheet-function vba

如果更改了cell1,我想使用worksheet_change()来运行macro1,如果更改了cell2,我想使用macro2等等。我知道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

但也没有运气。有什么帮助吗?

2 个答案:

答案 0 :(得分:6)

请参阅此示例。您必须使用Intersect来检查特定单元格是否已更改。我以A1A2A3

为例

我还建议您查看此link,告诉您在使用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

答案 1 :(得分:1)

这是一种方式:

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

或者如果您更喜欢选择案例语法,您可以选择以下路线:

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