【问题标题】:Excel macro combine two Worksheet_Change codeExcel 宏结合两个 Worksheet_Change 代码
【发布时间】:2017-09-04 22:37:07
【问题描述】:

我有两个有效的 Worksheet_Change 代码,我想在同一张工作表上使用它们。当我单独使用它们时,它们都可以工作,但是当我一起使用它们时,它们就不行了。我试图粘贴两个不同的代码,但我得到了一个模棱两可的名称检测错误。我还尝试使用 elseif,下一个但它们都不起作用。 两个代码:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Range("O:O"), Target) Is Nothing Then
        Cells(Target.Row, 17).Value = Date
    End If
End Sub

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    If Target.Column = 15 Then
        Range("P" & Target.Row).Value = Target.Value + Range("P" & Target.Row).Value
        Application.EnableEvents = False
        Target.Value = ""
        Application.EnableEvents = True
    End If
End Sub

感谢您的帮助

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    您可以将两个工作表更改事件放在同一个子中

    Private Sub Worksheet_Change(ByVal Target As Range)
            If Not Intersect(Range("O:O"), Target) Is Nothing Then
                Cells(Target.Row, 17).Value = Date
            End If
    
            If Target.Column = 15 Then
                Range("P" & Target.Row).Value = Target.Value + Range("P" & Target.Row).Value
                Application.EnableEvents = False
                Target.Value = ""
                Application.EnableEvents = True
            End If
        End Sub
    

    【讨论】:

      【解决方案2】:

      这样试试吧……

      Private Sub Worksheet_Change(ByVal Target As Range)
          If Target.CountLarge > 1 Then Exit Sub
          If Not Intersect(Range("O:O"), Target) Is Nothing Then
              Application.EnableEvents = False
              Cells(Target.Row, 17).Value = Date
              Range("P" & Target.Row).Value = Target.Value + Range("P" & Target.Row).Value
              Target.Value = ""
              Application.EnableEvents = True
          End If
      End Sub
      

      【讨论】:

      • @AndrásKrämer 您是否注意到您接受的答案与我提出的答案之间的区别?如果两种解决方案都有效,对您来说并不重要,重要的是,处理事件代码的正确方法应该是什么。如果您想在不寻求任何帮助的情况下编写下一个事件代码,那么您可以从我提出的代码中学到太多东西。 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-29
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      相关资源
      最近更新 更多