Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to interpret Application.Calculation

I am reviewing some VBA and came across the following code example. I don’t fully understand what this does and why it is implemented in this manner. Running the code doesn’t explain to me how this affects the macro or the Excel calculations. Can anyone here please explain to me what the Application.Calculation property does and how the following code affects Excel calculations in the macro iterations?

Sub example()

Dim CalculationMode As Integer
CalculationMode = Application.Calculation
Application.Calculation = xlCalculationManual

Do While 
  'Generic Do While statement
Loop

Application.Calculation = CalculationMode

End Sub

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your code:

  1. Stores the calculation setting: CalculationMode = Application.Calculation
  2. Turns calculation to manual: Application.Calculation = xlCalculationManual
  3. Iterates and does its thing.
  4. Restores the original calculation setting. Application.Calculation = CalculationMode

Here’s a testable example of whether formulas update after Application.Calculation = xlCalculationManual:

In a new blank sheet, in cell A1 enter the formula =B1, and in B1 enter a number like 5.

Testable code:

Sub whatever()
    Dim i As Long
    i = 1
    
    Dim arr(1 To 3) As Long
    arr(1) = 1
    arr(2) = 2
    arr(3) = 3
    
    Application.Calculation = xlCalculationManual
    
    Do While i <= 3
        Range("B1").Value = arr(i)
        Debug.Print Range("A1").Value
        i = i + 1
    Loop
    
    Application.Calculation = xlCalculationAutomatic
End Sub

The output in the Immediate Window is:

5
5
5

not

1
2
3

However, a counterexample could be the following:

    Dim arr(1 To 3) As String
    arr(1) = "=1"
    arr(2) = "=2"
    arr(3) = "=3"

    Application.Calculation = xlCalculationManual
    
    Do While i <= 3
        Range("A1").Formula = arr(i)
        Debug.Print Range("A1").Value
        i = i + 1
    Loop

where the Immediate Window returns:

1
2
3

i.e. the newly entered formula has been calculated.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading