2

如果 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

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

4

2 回答 2

6

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

我还建议您查看此链接,该链接告诉您在使用时需要注意什么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
于 2013-04-18T16:41:19.097 回答
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

或者,如果您更喜欢 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
于 2013-04-18T16:38:58.110 回答