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 :
Your code:
- Stores the calculation setting:
CalculationMode = Application.Calculation - Turns calculation to manual:
Application.Calculation = xlCalculationManual - Iterates and does its thing.
- 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.