单元格值更改时自动运行Excel VBA宏

时间:2019-03-21 19:09:43

标签: excel vba

我需要一个在单元格A1中的值更改时调用另一个宏的宏。 目前,我正在使用以下代码,但似乎每次页面重新计算时都会调用“ pageupdate”子项,而不仅仅是在A1中的值实际上从0更改为1时。

任何了解“ Worksheet_Calculate”子类型或if语句背后的逻辑的人是否都会遇到此问题?

Private Sub Worksheet_Calculate()
    '|-------------------------------------------------|
    '|        Run Pageupdate                           |
    '|-------------------------------------------------|

    'If cell A1 recalculates affected by a change in the sheet/s, then this macro runs the 'PageUpdate' Macro.
    'The point of this is to prevent the PageUpdate running when it doesn't need to.

    Static OldVal As Variant
    If Range("A1").Value <> OldVal Then
        OldVal = Range("A1").Value
        Call PageUpdate
    End If
End Sub

1 个答案:

答案 0 :(得分:-1)

  • 将以下子项添加为要附加到工作表的宏 受更新影响,并将您的代码放入此宏中。 You can find the solution here

      

    私有子工作表_更改(按目标的ByVal目标)       昏暗的KeyCell作为范围

    ' The variable KeyCells contains the cells that will
    ' cause an alert when they are changed.
    Set KeyCells = Range("A1:A1")
    
    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then
    
        ' Display a message when one of the designated cells has been
        ' changed.
        ' Place your code here.
        'MsgBox "Cell " & Target.Address & " has changed."
    
        End If 
    
         

    结束子