Skip to main content

Application.AfterCalculate event

Table of contents
  1. Syntax
  2. Remarks
  3. Examples

The AfterCalculate event occurs when all pending refresh activity (both synchronous and asynchronous) and all of the resultant calculation activities have been completed.

Syntax

expression.AfterCalculate

expression A variable that represents an Application object.

Remarks

This event occurs whenever calculation is completed and there are no outstanding queries. It's mandatory for both conditions to be met before the event occurs. The event can be raised even when there is no sheet data in the workbook, such as whenever calculation finishes for the entire workbook and there are no queries running.

Add-in developers use the AfterCalculate event to know when all the data in the workbook has been fully updated by any queries and/or calculations that may have been in progress.

This event occurs after all Worksheet.CalculateChart.CalculateQueryTable.AfterRefresh, and SheetChange events. It's the last event to occur after all refresh processing and all calc processing have completed, and it occurs after CalculationState is set to xlDone.

Examples

Put the following code in the ThisWorkbook object. Download This Example: Application AfterCalculate Event.

'-------------------- ThisWorkbook --------------------
Public WithEvents App As Application

Private Sub Workbook_Open()
    Set App = Application
End Sub

Private Sub App_AfterCalculate()
    ' DO WHATEVER YOU WANT After Calculate.  E.g., call a Public Sub.
    MsgBox "AfterCalculate called"
    Call RunAfterCalculate
End Sub

If the AfterCalculate handler modifies anything in the spreadsheet then, in order to prevent unexpected repeated or recursive callbacks, I wrap it in an If statement to make sure it only runs once, as in the following Module code:

'-------------------- Module --------------------
Public RunningAfterCalculate As Boolean

Public Sub RunAfterCalculate()
    If Not RunningAfterCalculate Then
        RunningAfterCalculate = True
        ' DO WHATEVER YOU WANT AfterCalculate
        ' ...
        MsgBox "Call RunAfterCalculate Once ..."
        
        RunningAfterCalculate = False
    End If
End Sub

Note that if for some reason VBA encounters an unhandled exception you will have to reset the App – e.g. by running a sub like this:

Public Sub RestartEventHandler()
    Set ThisWorkbook.App = Application
    Application.EnableEvents = True
    RunningAfterCalculate = False
End Sub

Another example: Excel Macro: Rename Worksheet Events in Excel

Leave a comment

Your email address will not be published. Required fields are marked *

Format your code: <pre><code class="language-vba">place your code here</code></pre>