简体   繁体   中英

How to use Excel VBA "Worksheet_Calculate" function for a range of cells

I want my macro to activate ONLY when a calculated cell in a SPECIFIED range changes. At the moment the macro activates whenever any cell on the sheet is calculated.

For example, how would I alter the following code so that Macro1 only activates when a cell in Range(A1:A5) changes due to a calculation, and not when cells in any other ranges are recalculated? Any guidance would be much appreciated.

Private Sub Worksheet_Calculate()
    Macro1
End Sub

This should do it...

Private Sub Worksheet_Calculate()
    Static last, test
    
    test = [sum(a1:a5)]
    
    If Not IsError(test) Then
        If last <> test Then
            last = test
            Macro1
        End If
    End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM