【问题标题】:Multiple targets with different macro calls in worksheet_change VBA codeworksheet_change VBA代码中具有不同宏调用的多个目标
【发布时间】:2013-04-11 21:24:07
【问题描述】:

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

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

【问题讨论】:

  • 不同的单元格是在同一张表还是不同的表?
  • 它们在同一张纸上
  • 好的 1 分钟...发布答案

标签: excel syntax-error worksheet-function vba


【解决方案1】:

请参阅此示例。您必须使用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

【讨论】:

  • Application.EnableEvents +1 以避免堆栈溢出
【解决方案2】:

这是一种方法:

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

【讨论】:

  • 我可以用宏调用替换 MsgBox Target.Address 吗?
  • 是的,只是将消息框放在那里作为示例。没有什么能阻止您在其中放置宏调用(或任何其他有效的 VBA 代码)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-01
  • 2012-07-13
相关资源
最近更新 更多