Worksheet_Change 事件未触发

NWT*_*ech 6 excel events vba onchange

我的 Excel 项目在家中正常运行(使用Excel 2010),但不能在两台工作计算机(使用Excel 2016)上正常运行,我怀疑Worksheet_Change事件是问题所在。

当用户进行更改时,黄色条(在屏幕截图中)应该再次变为白色,但事实并非如此。我在 2 台工作计算机上收到 2 种不同的响应。

代码中有两点需要指出:

  1. 在某些地方我使用vbColor扩展名,而在其他地方我必须使用数字代码。

  2. 一台计算机根本没有触发Worksheet_Change事件。我会注意到更改事件位于代码的顶部,尽管这与它无关。

我很感激建议和详细的解释,以帮助我学习。

截屏

Private Sub Worksheet_Change(ByVal Target As Range) 'Check for On-Time and Delays then change the Command Button Colors to show completed.  

'Return headers to white after jump to
Range("B3:I3,O3:V3,B28:I28,O28:V28,B53:I53,O53:V53,B78:I78,O78:V78,B103:I103,O103:V103,B128:I128,O128:V128,B153:I153,O153:V153").Interior.Color = vbWhite
'Check for On Time and Delayed Trips
'Trip 1 Scan Ready
If IsEmpty(Range("L3").Value) = False Then
    If Range("L3").Value > Range("I3").Value Then 'If actual is greater than Departure
        'If Delayed check for a delay code
        If IsEmpty(Range("L24").Value) Then 'If Delay code is missing
            Range("K24:L25").Interior.Color = 16711935
            CommandButton1.BackColor = 16711935
            CommandButton1.ForeColor = vbBlack
        Else 'If Delay Code is present check for delay time
            If IsEmpty(Range("L25").Value) Then
                Range("K24:L25").Interior.Color.Index = 16711935
                CommandButton1.BackColor = 16711935
                CommandButton1.ForeColor = vbBlack
            Else
                CommandButton1.BackColor = vbRed
                CommandButton1.ForeColor = vbWhite
                Range("K24:L25").Interior.Color = vbWhite
            End If
        End If
    Else
        'Flight was on Time
        CommandButton1.BackColor = 32768 '32768 = Green
        CommandButton1.ForeColor = vbWhite
        Range("K24:L25").Interior.Color = vbWhite
    End If
End If
Run Code Online (Sandbox Code Playgroud)

ash*_*awg 6

可能有多种因素导致此问题。一种诊断方法是像这样进行故障排除:

在您的程序开始时,就在此行之后:

Private Sub Worksheet_Change(ByVal Target As Range)
Run Code Online (Sandbox Code Playgroud)

...添加一个临时行:

MsgBox "Changed: " & Target.Address
Run Code Online (Sandbox Code Playgroud)

...然后在您的工作表中更改某些内容(任何更改都不会像您期望的那样触发事件)。

将发生两件事之一

  1. 您将弹出一个消息框,显示刚刚更改的任何内容的单元格引用。
    这表明事件正在正确触发,因此问题必须出在您随后的代码中。

  2. 或者,您不会弹出消息框。这表明事件没有触发,这可能是由以下几种可能性引起的:

    • 工作簿中的宏是否完全禁用?这通常是在从外部来源收到的工作簿上自动完成的。将工作簿保存到本地计算机或网络上的受信任位置(而不是从电子邮件中打开)。其他部分的代码运行正常吗?当您关闭/重新打开文件时,您是否收到有关宏安全性的警告?另外,尝试重新启动计算机。

    • 其他安全设置可能是一个问题。你曾经在这些机器上运行过 VBA 吗?您可以确认确保代码能够在擅长的安全设置中运行:
      FileOptions? Trust Center? Trust Center Settings?Macro Settings

      除了确保在那里启用宏之外,您还可以检查Trusted Locations信任中心,并将您的文档保存在列出的位置,或添加一个新位置。将“减少”保存在这些位置的文档的安全设置。

    • 是否EnableEvents在您的代码中的其他地方被有意禁用?如果你写了所有的代码,你应该知道你是否EnableEvents = False在某个时候设置了。也许它是故意的,但它没有被重新启用。

请记住暂时删除您添加的行,否则每次更改时都会弹出 MsgBox 很快就会变得烦人。:)

  • 要快速测试 EnableEvents 部分,您可以在即时窗口中键入 Application.EnableEvents = True,按 Enter,然后重试。 (2认同)