How can I write the vba code that will do the following: When I open a particular…
- User
How can I write the vba code that will do the following: When I open a particular workbook, I want that entire workbook to calculate and not other open workbooks.
- Assistant
You can write the following VBA code to achieve this:
- Open Visual Basic Editor by pressing Alt+F11.
- In the Project Explorer, double-click on the workbook that you want to modify.
- Choose "ThisWorkbook" from the dropdown list at the top of the editor.
- Copy and paste the following code:
Private Sub Workbook_Open() Application.Calculation = xlCalculationManual ThisWorkbook.ActiveSheet.Calculate End Sub
- Save your workbook and close the editor.
Explanation: When the workbook opens, the code sets the calculation mode to manual to prevent Excel from recalculating all open workbooks. Then, it forces the workbook to recalculate by calling the Calculate method on the active sheet.
Note: If you want to turn on automatic calculation after the workbook opens, simply add the following line to the code:
Application.Calculation = xlCalculationAutomatic
- User
I would like to calculate all the sheets of the particular woorkbook
- Assistant
To calculate all the sheets in the workbook when it opens, you can modify the VBA code as follows:
- Open the Visual Basic Editor by pressing Alt+F11.
- In the Project Explorer, double-click on the workbook that you want to modify.
- Choose "ThisWorkbook" from the dropdown list at the top of the editor.
- Copy and paste the following code:
Private Sub Workbook_Open() Application.Calculation = xlCalculationManual Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets ws.Calculate Next ws Application.Calculation = xlCalculationAutomatic End Sub
- Save and close the editor.
Explanation: When the workbook opens, the code sets the calculation mode to manual to prevent Excel from recalculating all open workbooks. Then, it loops through all the worksheets in the workbook and forces each one to recalculate using the Calculate method. Finally, it turns on automatic calculation.