Excel sheet for range calculation

Home / VBA / VBA Calculate (Cell, Range, Row, & Workbook)

By default, in Excel, whenever you change a cell value Excel recalculates all the cells that have a calculation dependency on that cell. But when you are using VBA, you have an option to change it to the manual, just like we do in Excel.

calculate-cell-value-using-vba

Using VBA Calculate Method

You can change the calculation to the manual before you start a code, just like the following.

Application.Calculation = xlManual

When you run this code, it changes the calculation to manual.

using-vba-calculate-method

And at the end of the code, you can use the following line of code to switch to the automatic.

Application.Calculation = xlAutomatic
switch-to-automatic-using-vba

You can use calculation in the following way.

calculation-method-vba-code
Sub myMacro()
    Application.Calculation = xlManual   
        'your code goes here   
    Application.Calculation = xlAutomatic
End Sub

Calculate Now (All the Open Workbooks)

If you simply want to re-calculate all the open workbooks, you can use the “Calculate” method just like below.

Calculate

Use Calculate Method for a Sheet

Using the following way, you can re-calculate all the calculations for all the

ActiveSheet.Calculate
Sheets("Sheet1").Calculate

The first line of code re-calculates for the active sheet and the second line does it for the “Sheet1” but you can change the sheet if you want.

Calculate for a Range or a Single Cell

In the same way, you can re-calculate all the calculations for a particular range or a single cell, just like the following.

Sheets("Sheet1").Range("A1:A10").Calculate
Sheets("Sheet1").Range("A1").Calculate

Return to VBA Code Examples

In this Article

  • Calculate Now
  • Calculate Sheet Only
  • Calculate Range
    • Calculate Individual Formula
  • Calculate Workbook
    • Calculate Workbook – Methods That Don’t Work

This tutorial will teach you all of the different Calculate options in VBA.

By default Excel calculates all open workbooks every time a workbook change is made. It does this by following a calculation tree where if cell A1 is changed, it updates all cells that rely on cell A1 and so on.  However, this can cause your VBA code to run extremely slowly, as every time a cell changes, Excel must re-calculate.

To increase your VBA speed, you will often want to disable automatic calculations at the beginning of your procedures:

Application.Calculation = xlManual

and re-enable it at the end:

Application.Calculation = xlAutomatic

However, what if you want to calculate all (or part) of your workbooks within your procedure?  The rest of this tutorial will teach you what to do.

Calculate Now

You can use the Calculate command to re-calculate everything (in all open workbooks):

Calculate

This is usually the best method to use. However, you can also perform more narrow calculations for improved speed.

Calculate Sheet Only

You can also tell VBA to calculate only a specific sheet.

This code will recalculate the active sheet:

ActiveSheet.Calculate

This code will recalculate Sheet1:

Sheets("Sheet1").Calculate

Calculate Range

If you require a more narrow calculation, you can tell VBA to calculate only a range of cells:

Sheets("Sheet1").Range("a1:a10").Calculate

Calculate Individual Formula

This code will calculate only an individual cell formula:

Range("a1").Calculate

Calculate Workbook

There is no VBA option to calculate only an entire workbook. If you need to calculate an entire workbook, the best option is to use the Calculate command:

Calculate

This will calculate all open workbooks.  If you’re really concerned about speed, and want to calculate an entire workbook, you might be able to be more selective about which workbooks are open at one time.

Calculate Workbook – Methods That Don’t Work

There are a couple of methods that you might be tempted to use to force VBA to calculate just a workbook, however none of them will work properly.

This code will loop through each worksheet in the workbook and recalculate the sheets one at a time:

Sub Recalculate_Workbook()
    Dim ws As Worksheet
    
    For Each ws In Worksheets
        ws.Calculate
    Next ws
End Sub

This code will work fine if all of your worksheets are “self-contained”, meaning none of your sheets contain calculations that refer to other sheets.

However, if your worksheets refer to other sheets, your calculations might not update properly.  For example, if you calculate Sheet1 before Sheet2, but Sheet1’s formulas rely on calculations done in Sheet2 then your formulas will not contain the most up-to-date values.

You might also try selecting all sheets at once and calculating the activesheet:

ThisWorkbook.Sheets.Select
ActiveSheet.Calculate

However, this will cause the same issue.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

Skip to content

VBA Range Calculate — Explained with Examples

We calculate the particular range using VBA. Calculate method in Excel help us to calculate all opened workbooks, specific workbooks, specific worksheets, Ranges, columns or rows. This method will be useful when your Excel Calculation method is set to manual mode. or if you have many formulas in the workbook and want to refresh or recalculate a particular range you can use Range.Calculate method.

VBA Caluclate Method Excel Range Object

VBA Range Calculate – Syntax

You can use the calculate method of the range to calculate any range.

Range(“YourRange”).Calculate

VBA Range Calculate – Examples

Here is the simple example to calculate a specific Range. This example will calculate Range “A2:D10” using VBA.

Sub VBA_Calculate_Range()
    Range("A2:D10").Calculate
End Sub

VBA Range Calculate – Instructions

Please follow the below step by step instructions to execute the above mentioned VBA macros or codes:

  1. Open an Excel Workbook from your start menu or type Excel in your run command
  2. Enter some formula at B2 as “=D2” and enter some value at D2. Now you can see the D2 value at B2.
  3. Set the caluclation mode to manual to test this macro
  4. Change the value at D2, now you can see that B2 value is not change even you have made changes at D2
  5. Press Alt+F11 to Open VBA Editor or you can goto Developer Table from Excel Ribbon and click on the Visual Basic Command to launch the VBA Editor
  6. Insert a Module from Insert Menu of VBA
  7. Copy the above code (for Calculating a Range using VBA) and Paste in the code window(VBA Editor)
  8. Save the file as Macro Enabled Workbook (i.e; .xlsm file format)
  9. Press ‘F5′ to run it or Keep Pressing ‘F8′ to debug the code line by line.

Now you can observe that the value at B2 is changed as per D2.

Calculate the Columns using VBA

Here is the simple example to calculate a specific Columns. This example will calculate the columns “A to D” using VBA.

Sub VBA_Calculate_Columns()
    Columns("A:D").Calculate
    'Or Range("A:D").Calculate
End Sub

Calculate the Rows using VBA

Here is the simple example to calculate a specific rows using VBA. This example will calculate the Rows”1 to 20″ using VBA.

Sub VBA_Calculate_Rows()
    Rows("1:20").Calculate
End Sub
Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:
By PNRaoLast Updated: March 2, 2023

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

Go to Top

Содержание

  1. Calculate Method of Worksheet Object VBA
  2. VBA Reference
  3. 120+ Project Management Templates
  4. Why we use Calculate Worksheet Method in VBA?
  5. VBA Calculate Worksheet Method- Syntax
  6. VBA Calculate Worksheet Method: All Open Workbooks
  7. VBA Calculate Worksheet Method: In Specific Sheet
  8. VBA Calculate Worksheet Method: In Specified Range
  9. VBA Calculate Worksheet Method: Instructions
  10. Controlling Calculation from VBA
  11. Controlling Calculation from VBA.
  12. Calculation Methods:
  13. F9 — Recalculate
  14. CTRL/ALT/F9 – Full Calculation
  15. Full Calculation with Dependency Rebuild
  16. Shift F9 – Sheet Recalculate
  17. Range Calculate: see Calculation Methods for details and limitations
  18. Evaluate Method:
  19. Evaluate Method limitations:
  20. Evaluate error handling:
  21. Properties controlling Calculation Options:
  22. Application.Calculation
  23. Excel’s Initial Calculation Setting
  24. Application.CalculateBeforeSave
  25. Application.Iteration, MaxIterations and MaxChange
  26. Workbook.PrecisionAsDisplayed
  27. Workbook.Date1904
  28. Workbook.AcceptLabelsInFormulas
  29. Worksheet.EnableCalculation; Preventing Specific Worksheets being Calculated
  30. Calculation Events:
  31. Application or Workbook SheetCalculate
  32. Worksheet or Chart Calculate
  33. Excel 2002/2003 Only
  34. Adding specified cells to the calculation list
  35. Checking Calculation Status
  36. Interrupting Calculation
  37. Application.CheckAbort
  38. Excel 2007 Only
  39. Controlling Multi-Threaded Calculation
  40. Range Calculate and RangeCalculateRowMajorOrder

Calculate Method of Worksheet Object VBA

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

50+ Excel Templates

50+ PowerPoint Templates

25+ Word Templates

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates
MS Word Pack
25+ Word PM Templates
Ultimate Project Management Template
Ultimate Resource Management Template
Project Portfolio Management Templates

Calculate Worksheet Method in VBA is used to calculate all open workbooks or a specific worksheet in a workbook or a specified range in a worksheet.

Why we use Calculate Worksheet Method in VBA?

If a workbook or a worksheet or a specific range has formulas we need to refresh each time when the values are changing. In that time we can use Calculate Worksheet Method in VBA.

VBA Calculate Worksheet Method- Syntax

Here is the example syntax to Calculate Worksheet method in Excel VBA.

Where Worksheet represents the object and Calculate is the method of worksheet object.

VBA Calculate Worksheet Method: All Open Workbooks

Please see the below VBA code to Calculate all open Workbooks. In this example we are using calculate method of application object.

VBA Calculate Worksheet Method: In Specific Sheet

Please see the below VBA code to Calculate in specified Worksheet named “Sheet1”.

VBA Calculate Worksheet Method: In Specified Range

Please see the below VBA code to Calculate in specified range (“A1:E10”) in a specified worksheet named “Sheet1”.

VBA Calculate Worksheet Method: Instructions

Please follow the below step by step instructions to execute the above mentioned VBA macros or codes:

  1. Open an Excel Worksheet
  2. Press Alt+F11 to Open VBA Editor
  3. Insert a Module from Insert Menu
  4. Copy the above code for activating worksheet and Paste in the code window(VBA Editor)
  5. Save the file as macro enabled Worksheet
  6. Press ‘F5’ to run it or Keep Pressing ‘F8’ to debug the code line by line and observe the calculations in the Worksheet.

Источник

Controlling Calculation from VBA

Smart Recalculation Evaluation Circumstances Calculation Process Dependency Trees
Controlling Calculation «CALCULATE» in Status Bar Calculation Methods Calculating from VBA
Volatile Functions & Actions User-Defined Functions Repetitive Calculation Version Timing Comparison

Controlling Calculation from VBA.

For information on what the calculation methods do see Calculation Methods.

VBA allows you to control Calculation methods, properties and events:

Calculation Methods:

F9 — Recalculate

CTRL/ALT/F9 – Full Calculation

In Excel 2000 and later versions:

In Excel 97 there are two possible methods using either SendKeys or EnableCalculation:

You can use SendKeys to send the CTRL/ALT/F9 key sequence. This can be tricky because Sendkeys just sends the keystrokes into the keyboard buffer, and they are not normally processed until VBA has ended and you cannot guarantee that they will be processed by the correct window/application etc.

With Windows 95/98/ME:

SendKeys «%^«, True

  • Use Sendkeys rather than Application SendKeys.
  • The True argument causes VBA to wait for the calculation to proceed without interruption. This is required unless the Sendkeys statement is that last VBA statement to be executed other than End.
  • The True argument does not work with Application.SendKeys

With Windows NT/2000/XP:

If the VBA procedure containing the Sendkeys statement is called directly or indirectly from a command button the True argument does not work, so you have to use DoEvents to get Win Xp and Excel97 to process them.

Another method uses the worksheet.enablecalculation property. When this property is changed all the formulae on the worksheet are flagged as uncalculated, so toggling the property to false and then back to true for all sheets in all open workbooks will cause the next calculation to be a full calculation.

Dim oSht as worksheet
Application.Calculation=xlCalculationManual

for each oSht in Worksheets
oSht.enablecalculation=false
osht.enablecalculation=true
next osht

You can also use this method for a single worksheet to do a full sheet calculate.

Full Calculation with Dependency Rebuild

In Excel 2002 and later versions: Application.CalculateFullRebuild

In prior versions of Excel you can achieve the same effect by switching to manual, replacing all equal signs in formulae with equal signs and then either switching back to automatic or doing a manual full calculation (Ctrl/Alt/F9)

Shift F9 – Sheet Recalculate

Range Calculate: see Calculation Methods for details and limitations

Evaluate Method:

You can use the Evaluate method of the Application, Worksheet or Chartobject to return the result of calculating a string containing Names, Ranges and/or a Formulae to VBA without altering anything on a worksheet. Evaluate also enables you to get the results of a single-cell or multi-cell array formula passed to Evaluate as a string. There are two different syntaxes for Application.Evaluate, for example as Evaluate(«SUM(A1:A20») or as [SUM(A1:A20)]

The difference between using Application.Evaluate and Worksheet.Evaluate is not spelled out in Excel’s help.
Application.Evaluate the string as though it was on the active sheet, but Worksheet.evaluate evaluates the string as though it was on the referenced sheet:
If Sheet1!A1 contains ‘fred’ and Sheet2!A1 contains ‘Joe’, and Sheet 1 is the active sheet then Evaluate(«A1») returns ‘fred’ but Worksheets(«Sheet2»).Evaluate(«A1») returns ‘Joe’

Evaluate Method limitations:

  • The string must be less than 256 characters.
  • A1 style references can be evaluated in both A1 and R1C1 reference mode (Application.ReferenceStyle), but R1C1 style references can only be evaluated in R1C1 mode.
  • Relative references in the string are treated as absolute, unless they are contained in defined names in which case the defined name is evaluated with respect to cell A1.
  • Dates should be in USA format (Month-Day-Year).
  • Evaluate always treats string formulae as array formulae.
  • Evaluate will return an error value if the string formulae contains external references to closed workbooks or XLM functions.
  • If the string formula is a reference to a UDF ( Evaluate(«=MyUdf()») ) it seems to be evaluated twice, but if its an expression containing a UDF and you are using Worksheet.Evaluate rather than Application.Evaluate ( Activesheet.Evaluate(«=0+MyUdf()») ) then it only gets evaluated once.
  • If the string formula contains a reference to both a UDF and a name it will fail with an error 2029 if the name reference occurs AFTER the UDF reference:
    • If fred is a named range and xyz() is a user defined VBA function then this statement returns error 2029: application.Evaluate(«=xyz(b1)+fred»)
    • This statement returns the correct value: application.Evaluate(«=fred+xyz(b1)»)
    • Microsoft KB article 823604 identifies this problem but does not correctly diagnose the circumstances that cause it.

You can bypass many of these limitations (at the cost of performance) by inserting the formula string into a worksheet cell and then reading the resulting cell value back into a VBA variable.

Evaluate error handling:

If Evaluate cannot evaluate the string it returns an error rather than raising an error, so to trap the error you need to assign the result to a variant and then check the variant using ISERROR.

Public Function EVAL(theInput As Variant) As Variant

‘ if UDF evaluate the input string as though it was on this sheet
‘ else evaluate for activesheet

Dim vEval As Variant
Application.Volatile
On Error GoTo funcfail
If not IsEmpty(theInput) then
If TypeOf Application.Caller.Parent Is Worksheet Then
vEval = Application.Caller.Parent.Evaluate(Cstr(theInput))
Else
vEval = Application.Evaluate(cstr(theInput))
End If
If IsError(vEval) Then
EVAL = CVErr(xlErrValue)
Else
EVAL = vEval
End If
End If
Exit Function
funcfail:
EVAL = CVErr(xlErrNA)
End Function

The EVAL function can be called either as a UDF or from VBA.
If the input string resolves to an array formula then EVAL will return the corresponding array of results.
EVAL must be volatile because Excel cannot detect which cells the input string argument refers to, and hence does not know when the function needs to be recalculated.
EVAL returns #Value if the string cannot be evaluated, and #N/A if the function encounters any other error.

Properties controlling Calculation Options:

Application.Calculation

Can be set to xlCalculationAutomatic, xlCalculationManual or xlCalculationSemiAutomatic, (in Excel95 these were xlAutomatic etc).
Resetting calculation to xlCalculationAutomatic will trigger a recalculation.

Setting these properties sometimes fails with a 1004 error when the code is called from the event code of a Control Toolbox control. You can bypass this problem by setting the TakeFocusonClick property of the control button to false, or for other controls by preceding it by Activesheet.Activate.

Excel’s Initial Calculation Setting

FastExcel V4 allows you to control Excel’s initial calculation sequence.

Excel sets the initial calculation mode from the first non-template, non-addin workbook opened, or created and calculated.

This means that the calculation mode setting in subsequently opened workbooks will be ignored.

If you need to override the way Excel initially sets the calculation mode you can set it yourself by creating a module in ThisWorkbook (doubleclick ThisWorkbook in the Project Explorer window in the VBE), and adding this code. This example sets calculation to Manual.

Private Sub Workbook_Open()
Application.Calculation = xlCalculationManual
End Sub

Unfortunately if calculation is set to Automatic when a workbook containing this code is opened, Excel will start the recalculation process before the Open event is executed. The only way I know of to avoid this is to open a dummy workbook with a Workbook open event which sets calculation to manual and then opens the real workbook.

Application.CalculateBeforeSave

True or False. If calculation is Manual and CalculateBeforeSave is true when you Save the workbook it will be recalculated.

Application.Iteration, MaxIterations and MaxChange

If Application.Iteration is true and the workbook contains circular references, then calculation will iterate until either the number of iterations reaches MaxIterations or the largest change in cell value in the latest iteration is less than Maxchange.

Workbook.PrecisionAsDisplayed

If True the workbook will be calculated using the number of decimal places in the formatting.

Workbook.Date1904

If true date calculations in the workbook will be based on 1904.

Workbook.AcceptLabelsInFormulas

If true Excel will use «Natural Language» labels in formulae. For anything other than simple models this should be turned off.

Worksheet.EnableCalculation; Preventing Specific Worksheets being Calculated

FastExcel Version 4 gives you an improved implementation of this facility, called Mixed Mode sheets, which allows you to control which sheets will be recalculated by which type of calculation event, and saves your settings with the workbook.

Setting the Worksheet property EnableCalculation to False will prevent Excel from including the worksheet in a recalculation. This will stop the sheet being recalculated by Automatic Recalculation, F9, Ctrl/Alt/F9 and by Sheet.Calculate, Application.Calculate, Application.CalculateFull and Application.CalculateFullRebuild. The EnableCalculation property has no effect on Range.Calculate.

If you use Range.Calculate on a formula on a worksheet that has EnableCalculation set to false then at the next recalculation Excel will recalculate any formulae on other sheets that are dependent on that formula.

Setting enablecalculation to false and then back to true will flag all the formulae on the worksheet as uncalculated. If the calculation mode is Automatic a recalculation will be triggered. All calculation methods, including Sheet.Calculate but excluding Range.Calculate, will then calculate all the formulae on the sheet. You can use this method as a way of simulating Calculatefull at worksheet rather than workbook level. Note that Sheet.Calculate will not reset the uncalculated formulae flags, so two Sheet.Calculates in succession after toggling the EnableCalculation property will both do a Full Sheet Calculate.

The property is reset to true when a workbook is opened.

Calculation Events:

Application or Workbook SheetCalculate

This event occurs after any worksheet is recalculated or changed chart data is replotted.

Worksheet or Chart Calculate

This event occurs after the Worksheet is recalculated or the chart’s changed data is replotted.

Excel 2002/2003 Only

Excel 2002/2003 considerably enhances your ability to control calculation from VBA:

Adding specified cells to the calculation list

You can use Range.Dirty to add the specified cells to the list of cells requiring calculation at the next recalculation.
There is a bug in Range.Dirty. It always acts on the currently active worksheet rather than the worksheet the Range object actually refers to.

Checking Calculation Status

The Application.CalculationState property allows you to check if calculation has completed ( xlDone ), is pending ( xlPending ) , or is in process ( xlCalculating ). The Pending state seems to correspond to the message Calculate in the statusbar: for workbooks with more than 65536 dependencies the CalculationState is always xlPending or xlCalculating.

Interrupting Calculation

You can control the users ability to interrupt calculation by specifying what will interrupt the calculation.

Application.CalculationInterruptKey= XlAnyKey | XLEscKey | XlNokey

You can also control error handling of the interrupt (in Excel 97 onwards) using

Application.EnableCancelKey= xlDisabled | xlErrorHandler | xlInterrupt

Application.CheckAbort

According to Help Application.Checkabort is supposed to stop recalculation except for a specified range. It does not do this. Apparently it throws a runtime error if there are pending abort messages in the app message queue (mouse clicks, esc key down etc). The parameter specifies whether to eat the message or leave it in the queue. The objective is to allow a a long-running VBA calculation to be interrupted in the same way as an Excel calculation.

Excel 2007 Only

Controlling Multi-Threaded Calculation

You can control Excel 2007’s new multithreaded calculation from VBA using Application.MultiThreadedCalculation .

Application.MultiThreadedCalculation.Enabled can be True or False to turn on/off multi-threaded calculation.

Application.MultiThreadedCalculation.ThreadMode can be xlThreadModeAutomatic or xlThreadModeManual.
if set to Manual then Application.MultiThreadedCalculation.ThreadCount can be set to the number of threads to use.

Range Calculate and RangeCalculateRowMajorOrder

Excel 2007 has two Range calculation methods. There is no standard user interface for running these calculation methods: you must call them by using VBA or some other programming language. These methods are useful when you want to calculate only a small block of cells while leaving all other formulas unchanged.

Источник

The Range.Calculate methods are very useful additions to Excel’s other calculation methods (Application level Calculate, CalculateFull, CalculateFullRebuild and Worksheet.calculate: the missing one is Workbook.Calculate!).

You can use the Range Calculate methods to:

  • Force calculation of a block of formulas or a single formula
  • See how long the variations of a particular formula take to calculate
  • Speed up repeated calculations

Download my RangeCalc Addin

You can download my RangeCalc addin from my website’s downloads page (xla password is dm).

This adds a button to the addins tab which uses Range.Calculate to time calculation of the currently selected cells.

Inspecting the RangeCalc code: different problems with different versions

You can unlock the xla to view the code using a password of dm.
The code in the RangeCalc sub bypasses a number of Range.calculate quirks in various Excel versions:

Sub RngTimer()
 '
 ' COPYRIGHT © DECISION MODELS LIMITED 2000,2001. All rights reserved
 '
 ' timed calculation of selected Range
 '
 ' bypass grouped and interactive problem 17/10/00
 ' remove interactive=false: Excel 97 Hangs when UDF error 14/2/01
 ' fix for application.iteration and array formulae with Excel2002 29/10/2001
 '
 Dim dRangeTime As Double
 Dim iMsg As Integer
 Dim blIter As Boolean
 Dim oCalcRange As Range ''' range to calculate
 Dim dOvhd As Double
 Dim strMessage As String
 '
 ' store iteration property
 '
 blIter = Application.Iteration
 '
 If ActiveWorkbook Is Nothing Or ActiveSheet Is Nothing Or ActiveWindow Is Nothing Or Selection Is Nothing Then
 Exit Sub
 Else
 If TypeName(Selection) = "Range" Then
 '
 ' if Excel2002 or greater handle iteration problem
 '
 If Left(Application.Version, 1) = "1" Then
 '
 ' switch off iteration
 '
 Application.Iteration = False
 End If
 '
 ' expand selected range to include all of any multicell array formula
 ' - makes Excel 2002 behave like earlier versions
 ' - allows notification if range has been expanded
 '
 Call ExpandRange(Selection, oCalcRange)
 '
 On Error GoTo errhandl
 '
 dOvhd = MicroTimer ''' ensure frequency is initialised
 dOvhd = MicroTimer ''' get time
 dOvhd = MicroTimer - dOvhd ''' calc microtimer overhead
 '
 dRangeTime = MicroTimer
 oCalcRange.Calculate
 dRangeTime = MicroTimer - dRangeTime - dOvhd
 '
 On Error GoTo 0
 '
 dRangeTime = Int(dRangeTime * 100000) / 100
 '
 ' 16/11/2009 - bypass multi-cell array formula problem
 '
 If Val(Application.Version) > 9 And Val(Application.Version) < 12 Then
 oCalcRange.Dirty
 End If
 '
 ' change message if array formula caused expansion of selection
 '
 If oCalcRange.Count = Selection.Count Then
 strMessage = CStr(Selection.Count) & " Cell(s) in Selected Range "
 Else
 strMessage = CStr(oCalcRange.Count) & " Cell(s) in Expanded Range "
 End If
 iMsg = MsgBox(strMessage & CStr(dRangeTime) & " Milliseconds", vbOKOnly + vbInformation, "RangeCalc")
 End If
 End If
 Application.Iteration = blIter ''' restore setting
 Set oCalcRange = Nothing
 Exit Sub
 errhandl:
 On Error GoTo 0
 Application.Iteration = blIter ''' restore setting
 Set oCalcRange = Nothing
 iMsg = MsgBox("Unable to Calculate Range", vbOKOnly + vbCritical, "RangeCalc")
 End Sub

Circular References

Using Range.Calculate on ranges that contain circular references within the range fails in Excel versions before Excel 2007.
In Excel 2007 and later Range.calculate only does a single iteration of the circular reference in Manual calculation mode, regardless of the Iteration settings.
So the RangeCalc addin switches iteration off whilst doing the Range.Calculate.

Multiple Sheets Selected

If you have multiple sheets selected Range.Calculate fails with a 1004 error, so the RangeCalc code has an error trap and message for any failure in Range.Calculate.

Multiple Areas selected  on a single Sheet

Range.Calculate will happily calculate a multi-area selection as long as all the areas are on the same sheet.

Multi-Cell Array formulas

If you do not select all the cells in a multi-cell array formula Range.Calculate will fail. My RangeCalc addin solves this problem by:

  • Automatically expanding the range to calculate to include all the cells in any array formula which intersects the selected range
  • Notifying the user that the range has been expanded

The VBA code to exapnd the range looks like this:

Sub ExpandRange(oStartRange As Range, oEndRange As Range)
 '
 ' COPYRIGHT © DECISION MODELS LIMITED 2000,2001. All rights reserved
 '
 ' Input: oStartRange, a range object that may or may not contain array formulae
 ' Output: oEndRange, a range object that has been expanded -
 ' to include all the cells in any array formula that is partly in the range
 '
 Dim oCell As Range
 Dim oArrCell As Range
 '
 ' loop on cells in oStartRange
 ' and expand range to include all the cells in any array formulae
 '
 On Error Resume Next
 '
 Set oEndRange = oStartRange
 For Each oCell In oStartRange
 If oCell.HasArray = True Then
 For Each oArrCell In oCell.CurrentArray
 '
 ' add any extra array cells
 '
 If Intersect(oEndRange, oArrCell) Is Nothing Then
 '
 ' if this cell is not in the expanded range then add it
 '
 Set oEndRange = Union(oEndRange, oArrCell)
 End If
 Next oArrCell
 End If
 Next oCell
 Set oCell = Nothing
 Set oArrCell = Nothing
 End Sub

There is also another problem with multi-cell array formulas and Range.Calculate, but it only exists in Excel 2002 and 2003 (after a Range.Calculate the array formula gets evaluated once for each cell it occupies in all subsequent recalculations). This problem is bypassed by using Range.Dirty on the range!

Note: The bug in Range.Dirty  is still there in Excel 2013. (it always works on the active sheet even when the range refers to another sheet!)

Range.Calculate and Range.CalculateRowMajorOrder – different handling of within-range dependencies

In early Excel versions (Excel 97 and 2000) Range.Calculate used a very simple calculation method: calculate the cells in each row in turn from left to right and ignore any forward references or within range dependencies. This method is fine as long as you know thats what it does and arrange your formulas accordingly (otherwise you may get incorrect results)!

But some people thought this was a bug, so it got fixed in Excel 2002 and 2003 (and later versions): Range.Calculate now starts by doing the left-to right calculation on each row in turn, and then starts recalculating any cells that refer to uncalculated cells within the range. In other words it achieves the same result as the standard Excel recalculation method.

The only problem was that this made Range.Calculate slower than in previous versions: and so some customers refused to upgrade because they could not run their bump runs fast enough!

So in Excel 2007 Microsoft solved the problem by introducing Range.CalculateRowMajorOrder. This method worked exactly the same way as the Excel 97 versions of Range.Calculate and was faster than the new Range.Calculate, and so everyone was happy except the VBA coders who had to work out when to use which method.

Some more Range.Calculate Limitations

Whilst the 2 Range Calculate methods are very useful, they do have some limitations:

  • They are both single-threaded calculation methods (In todays world this a serious limitation)
  • There is no keystroke sequence to initiate them from the UI (FastExcel uses Alt-F9 for this)
  • Re-entrant use of Range.Calculate is not allowed: for instance you can’t call Range.Calculate from inside a UDF
  • Range.Calculate works in US english dates etc.

Summary

  • Range.Calculate and Range.CalculateRowMajorOrder can be fast calculation methods
  • But they are not multi-threaded
  • For me they are essential tools for comparing formula speed
  • They need a bit of wrapping code, as in my RangeCalc addin, to make them generally useful.

Like this post? Please share to your friends:
  • Excel return value from array
  • Excel sheet for java
  • Excel select a range of cells vba excel
  • Excel sheet for balance sheet
  • Excel seconds to date