Excel обновить все формулы vba

I have a problem in refreshing the cell’s calculation.

In other words, I have many columns where i have a formula or macro in each one of them.

But the problem is that i should absolutely activate the option » automatic calculation» in the excel options or i should save then the new results appear.

Now, I would insert something in the macro that can refresh me the results instantaneously.

Thanks

R3uK's user avatar

R3uK

14.4k7 gold badges43 silver badges77 bronze badges

asked Aug 12, 2015 at 7:58

Souma's user avatar

1

You could simply press :

F9 to calculate the whole active workbook

Shift + F9 to calculate the active sheet


Anyway, here are the different options with .Calculate :

Sub Souma()

'Use this to calculate all the open workbooks
Application.Calculate

'Use this to calculate the whole sheet, called "Sheet1"
ThisWorkbook.Worksheets("Sheet1").Calculate


'Use this to calculate the cell A1 on the sheet called "Sheet1"
ThisWorkbook.Worksheets("Sheet1").Range("A1").Calculate
'Use this to calculate the range A1 to D10 on the sheet called "Sheet1"
ThisWorkbook.Worksheets("Sheet1").Range("A1:D10").Calculate
'Use this to calculate the column A on the sheet called "Sheet1"
ThisWorkbook.Worksheets("Sheet1").Columns(1).Calculate
'Use this to calculate the row 1 on the sheet called "Sheet1"
ThisWorkbook.Worksheets("Sheet1").Rows(1).Calculate

End Sub

answered Aug 12, 2015 at 8:20

R3uK's user avatar

R3uKR3uK

14.4k7 gold badges43 silver badges77 bronze badges

4

Copy and paste the code below to your VBA project:

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

This code should automatically run after you open the Excel file, enabling automatic calculation in all opened files.

answered Aug 17, 2015 at 20:01

Paulo's user avatar

PauloPaulo

1001 silver badge12 bronze badges

 

Иван Фильченков

Пользователь

Сообщений: 208
Регистрация: 27.12.2012

#1

23.07.2016 10:39:24

Доброго всем времени суток.
Прошу помощи в решение проблемки.
Есть макрос, он подставляет значение и выводит на печать определенные листы, выполняет это в цикличности.
Т.е. вставил значение — отправил на печать, следущее вставил — отправил на печать.
Но файл большой и он не успевает обновить все формулы (пересчитать)
Как прописать в макросе после подстановки значения пересчет формул?
Макрос прилагаю

Код
Sub АОСР()

    Dim c As Range, el
    Application.ScreenUpdating = False
    With Sheets("ФормаСети")
        For Each c In .Range(.Range("F57"), .[F57].End(xlDown)).Cells
            Sheets("ФОРМА").Range("DF123") = c.Value
            Sheets(Array("1ГидИз1", "2Гео", "3ГидИз2", "3ГидИз2", "4Тран", "5РазрТрКол", "6ПеОснКол", "7ПеОснКан", "8МонтТруб", "9БетЗам", "10ОбЗасПеТр", "11БетЛот", "12ШтукКол", "13МонтКол", "14ОбрЗасПеКол", "15МонГол", "16ОбрЗасГрТр", "17ОбрЗасГрКол")).Select
            ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
                ThisWorkbook.Path & Application.PathSeparator & c.Value & ".pdf", Quality:=xlQualityStandard, _
                IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
        Next
    End With
    Application.ScreenUpdating = True
End Sub
 

JayBhagavan

Пользователь

Сообщений: 11833
Регистрация: 17.01.2014

ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64

#2

23.07.2016 10:51:22

Если стоит автомат. пересчёт, то перед печатью добавьте строку:

Код
doevents

<#0>
Формула массива (ФМ) вводится Ctrl+Shift+Enter
Memento mori

 

Извините я полный профан в макросах, это перед какой строчкой?

 

JayBhagavan

Пользователь

Сообщений: 11833
Регистрация: 17.01.2014

ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64

Попробуйте между 7 и 8 строками.

<#0>
Формула массива (ФМ) вводится Ctrl+Shift+Enter
Memento mori

 
 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

 

Karataev

Пользователь

Сообщений: 2306
Регистрация: 23.10.2014

#7

23.07.2016 11:16:27

Если формулы только на листе «ФОРМА»:

Скрытый текст

Если формулы на листе «ФОРМА» и на тех листах, которые Вы выделяете:

Скрытый текст

P.S. Я из цикла убрал выделение листов, чтобы каждый раз листы не выделялись, т.к. достаточно выделить один раз.
Коды не тестировал, поэтому возможны опечатки или ошибки.

 

спасибо, сейчас попробую
не не изменяет, не пересчитывает (((

Изменено: Иван Фильченков23.07.2016 11:33:58

 

Karataev

Пользователь

Сообщений: 2306
Регистрация: 23.10.2014

#9

23.07.2016 11:45:45

Пересчет на всех листах активной книги и на всех листах всех других открытых книг:

Код
Sub АОСР()
    Dim c As Range, el
    Application.ScreenUpdating = False
    Sheets(Array("1ГидИз1", "2Гео", "3ГидИз2", "3ГидИз2", "4Тран", "5РазрТрКол", "6ПеОснКол", "7ПеОснКан", "8МонтТруб", "9БетЗам", "10ОбЗасПеТр", "11БетЛот", "12ШтукКол", "13МонтКол", "14ОбрЗасПеКол", "15МонГол", "16ОбрЗасГрТр", "17ОбрЗасГрКол")).Select
    With Sheets("ФормаСети")
        For Each c In .Range(.Range("F57"), .[F57].End(xlDown)).Cells
            Sheets("ФОРМА").Range("DF123") = c.Value
            Application.Calculate
            ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
                ThisWorkbook.Path & Application.PathSeparator & c.Value & ".pdf", Quality:=xlQualityStandard, _
                IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
        Next
    End With
    Application.ScreenUpdating = True
End Sub
 

JayBhagavan

Пользователь

Сообщений: 11833
Регистрация: 17.01.2014

ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64

Попробуйте после пересчёта добавить рекомендуемую мной ранее команду.

<#0>
Формула массива (ФМ) вводится Ctrl+Shift+Enter
Memento mori

 

не пересчитывает, пересчитывает только после первой подстановке (((

 

JayBhagavan

Пользователь

Сообщений: 11833
Регистрация: 17.01.2014

ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64

Иван Фильченков, сделайте файл-пример и приложите к теме, чтобы не гадать больше. И озвучьте что у Вас за офис (год, разрядность) и ОС.

<#0>
Формула массива (ФМ) вводится Ctrl+Shift+Enter
Memento mori

 

Karataev

Пользователь

Сообщений: 2306
Регистрация: 23.10.2014

#13

23.07.2016 12:11:46

Может быть убрать ScreenUpdating. В этом коде нет обновления формул (то есть это Ваш первоначальный код, только я вынес из цикла выделение листов):

Код
Sub АОСР()
    Dim c As Range, el
    Sheets(Array("1ГидИз1", "2Гео", "3ГидИз2", "3ГидИз2", "4Тран", "5РазрТрКол", "6ПеОснКол", "7ПеОснКан", "8МонтТруб", "9БетЗам", "10ОбЗасПеТр", "11БетЛот", "12ШтукКол", "13МонтКол", "14ОбрЗасПеКол", "15МонГол", "16ОбрЗасГрТр", "17ОбрЗасГрКол")).Select
    With Sheets("ФормаСети")
        For Each c In .Range(.Range("F57"), .[F57].End(xlDown)).Cells
            Sheets("ФОРМА").Range("DF123") = c.Value
            ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
                ThisWorkbook.Path & Application.PathSeparator & c.Value & ".pdf", Quality:=xlQualityStandard, _
                IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
        Next
    End With
End Sub

Изменено: Karataev23.07.2016 12:13:02

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

Иван Фильченков, Calculate пробовали?

 

Karataev

Пользователь

Сообщений: 2306
Регистрация: 23.10.2014

Юрий М, да я предлагал Calculate в постах 7 и 9.

 

Karataev

Пользователь

Сообщений: 2306
Регистрация: 23.10.2014

#16

23.07.2016 12:15:16

Цитата
Иван Фильченков написал:
пересчитывает только после первой подстановке (((

а в каком коде пересчитывает? В Вашем исходном или в том, который я предложил? Или при использовании DoEvents?

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

#17

23.07.2016 12:19:56

Цитата
Karataev написал:
Юрий М, да я предлагал Calculate в постах 7 и 9

Я вижу, но мой вопрос автору темы )

 

Раньше был мой исходный код и он пересчитывался. Сейчас файл большой 20 метров и много связей как и листов и он перестал все пересчитывать.
Офис 13

 

Да делал, пересчета после подстановки нет (

 

Karataev

Пользователь

Сообщений: 2306
Регистрация: 23.10.2014

Иван Фильченков, а код из поста 13 пробовали? Только у Вас должен быть включен автоматический пересчет формул: вкладка «Формулы» — Параметры вычислений — Автоматически.

 

Юрий М

Модератор

Сообщений: 60570
Регистрация: 14.09.2012

Контакты см. в профиле

#21

23.07.2016 12:35:21

Цитата
Karataev написал: у Вас должен быть включен автоматический пересчет формул

Думаю, что автор проверил это первым делом.

 

Я конечно чайник, но действительно сразу проверил

 

Karataev

Пользователь

Сообщений: 2306
Регистрация: 23.10.2014

Иван Фильченков, ну так что, Вы тестировали код из поста 13?

 

Попробовал, результат тот же, не пересчитывает ((

 

Karataev

Пользователь

Сообщений: 2306
Регистрация: 23.10.2014

#25

23.07.2016 14:30:42

Может быть какие-нибудь косвенные действия делать, чтобы обновились формулы. Попробуйте такой способ:

Скрытый текст

 

Попробовал, не обновляет.
Странно то что мой исходный файл раньше работал и все обновлялось. Что же может быть такое?? ((

 

Karataev

Пользователь

Сообщений: 2306
Регистрация: 23.10.2014

#27

23.07.2016 14:49:57

А так? Макрос сохраняет файл после каждого изменения ячейки «DF123»:

Скрытый текст

 

Извини за дурацкий вопрос, я в макросах совсем ни как, но он где должен быть записан, сейчас он у меня торчит в Module4. Это может как то сказаться на его работоспособности?
Последний тоже код не обновляет ((

Изменено: Иван Фильченков23.07.2016 15:20:04

 

Karataev

Пользователь

Сообщений: 2306
Регистрация: 23.10.2014

Вставьте его туда, где у Вас был Ваш код.

 

Karataev

Пользователь

Сообщений: 2306
Регистрация: 23.10.2014

#30

23.07.2016 15:01:14

А вручную, когда Вы изменяете ячейку «DF123», формулы обновляются сейчас?

How do you get spreadsheet data in Excel to recalculate itself from within VBA, without the kluge of just changing a cell value?

braX's user avatar

braX

11.5k5 gold badges20 silver badges33 bronze badges

asked Sep 30, 2008 at 18:54

Lance Roberts's user avatar

Lance RobertsLance Roberts

22.2k32 gold badges112 silver badges129 bronze badges

The following lines will do the trick:

ActiveSheet.EnableCalculation = False  
ActiveSheet.EnableCalculation = True  

Edit: The .Calculate() method will not work for all functions. I tested it on a sheet with add-in array functions. The production sheet I’m using is complex enough that I don’t want to test the .CalculateFull() method, but it may work.

MarredCheese's user avatar

MarredCheese

16.6k8 gold badges89 silver badges87 bronze badges

answered Sep 30, 2008 at 18:54

Lance Roberts's user avatar

Lance RobertsLance Roberts

22.2k32 gold badges112 silver badges129 bronze badges

4

This should do the trick…

'recalculate all open workbooks
Application.Calculate

'recalculate a specific worksheet
Worksheets(1).Calculate

' recalculate a specific range
Worksheets(1).Columns(1).Calculate

answered Sep 30, 2008 at 19:26

Graham's user avatar

1

Sometimes Excel will hiccup and needs a kick-start to reapply an equation. This happens in some cases when you are using custom formulas.

Make sure that you have the following script

ActiveSheet.EnableCalculation = True

Reapply the equation of choice.

Cells(RowA,ColB).Formula = Cells(RowA,ColB).Formula

This can then be looped as needed.

answered Sep 4, 2013 at 19:11

kambeeks's user avatar

kambeekskambeeks

811 silver badge2 bronze badges

You might also try

Application.CalculateFull

or

Application.CalculateFullRebuild

if you don’t mind rebuilding all open workbooks, rather than just the active worksheet. (CalculateFullRebuild rebuilds dependencies as well.)

answered Sep 30, 2008 at 19:52

Dave DuPlantis's user avatar

Dave DuPlantisDave DuPlantis

6,3543 gold badges27 silver badges30 bronze badges

I had an issue with turning off a background image (a DRAFT watermark) in VBA. My change wasn’t showing up (which was performed with the Sheets(1).PageSetup.CenterHeader = "" method) — so I needed a way to refresh. The ActiveSheet.EnableCalculation approach partly did the trick, but didn’t cover unused cells.

In the end I found what I needed with a one liner that made the image vanish when it was no longer set :-

Application.ScreenUpdating = True

answered Dec 2, 2014 at 17:28

AjV Jsy's user avatar

AjV JsyAjV Jsy

5,6994 gold badges34 silver badges30 bronze badges

After a data connection update, some UDF’s were not executing. Using a subroutine, I was trying to recalcuate a single column with:

Sheets("mysheet").Columns("D").Calculate

But above statement had no effect. None of above solutions helped, except kambeeks suggestion to replace formulas worked and was fast if manual recalc turned on during update. Below code solved my problem, even if not exactly responsible to OP «kluge» comment, it provided a fast/reliable solution to force recalculation of user-specified cells.

Application.Calculation = xlManual
DoEvents
For Each mycell In Sheets("mysheet").Range("D9:D750").Cells
    mycell.Formula = mycell.Formula
Next
DoEvents
Application.Calculation = xlAutomatic

answered Jun 24, 2019 at 22:28

pghcpa's user avatar

pghcpapghcpa

83311 silver badges25 bronze badges

0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
Dim excelNimi As String
Dim Massiv_price(100) As Single
Dim Massiv_type() As Variant
 
Private Sub CommandButton1_Click()
'сохранение типов устройств в массив
Massiv_type = ActiveSheet.Range(Cells(2, 1), Cells(100, 1)).Value
 
'сохранение цен на устройства в другой массив
For i = 2 To 100
    If ActiveSheet.Cells(i, 4).Value <> 0 Then
    Massiv_price(i) = ActiveSheet.Cells(i, 4).Value
    End If
Next
 
'поэтапное открытие файлов в папке и внесение в них изменений (уже и не помню кого благодарить за эту часть кода):
    Dim sFolder As String, sFiles As String
    With Application.FileDialog(msoFileDialogFolderPicker)
        If .Show = False Then Exit Sub
        sFolder = .SelectedItems(1)
    End With
    sFolder = sFolder & IIf(Right(sFolder, 1) = Application.PathSeparator, "", Application.PathSeparator)
    Application.ScreenUpdating = False
    sFiles = Dir(sFolder & "*.xlsx")
    Do While sFiles <> ""
        Workbooks.Open sFolder & sFiles
Application.Volatile True
ThisWorkbook.ActiveSheet.Columns("J:K").Calculate
 
    'Столбец стоимость yhteensä-sarake:
    ActiveSheet.Cells(7, 10).Value = "yhteensä"
    'Столбец цена hinta-sarake:
    ActiveSheet.Cells(7, 9).Value = "á hinta"
   
 
'Поиск таких же типов и присвоение им цены:
For i = 8 To 100
    For j = 1 To 99
            If ActiveSheet.Cells(i, 5).Value = "" Then
            'выход из цикла поиска совпадений, если все типы в столбце перебраны:
            GoTo NextOsaluettelo
            End If
                'Если совпадение по типу найдено:
                If ActiveSheet.Cells(i, 5).Value = Massiv_type(j, 1) Then
                'вставить соответствующую типу цену, округлив ее до двух знаков после запятой:
                ActiveSheet.Cells(i, 9).Value = WorksheetFunction.Round(Massiv_price(j + 1), 2)
                'поменять типы ячеек в столбцах количесвто (No. of units), цена (á hinta) и стоимость (yhteensä):
                ActiveSheet.Cells(i, 10).NumberFormat = "General"
                ActiveSheet.Cells(i, 9).NumberFormat = "General"
                ActiveSheet.Cells(i, 8).NumberFormat = "General"
                'посчитать стоимость:
                ActiveSheet.Cells(i, 10).Value = "=H" & i & "*I" & i
                End If
    Next
Next
 
NextOsaluettelo:
ActiveSheet.Cells(i + 1, 8).Value = "Kilvet"
ActiveSheet.Cells(i, 10).NumberFormat = "General"
ActiveSheet.Cells(i + 1, 10).NumberFormat = "General"
ActiveSheet.Cells(i + 1, 10).Value = "5"
 
'расчет суммы стоимости всего изделия:
ActiveSheet.Cells(i + 3, 8).Value = "Materiaalit yht."
ActiveSheet.Cells(i + 3, 10).Select
ActiveSheet.Cells(i + 3, 10).NumberFormat = "General"
ActiveSheet.Cells(i + 3, 10) = "=SUMMA(J8:J" & i + 1 & ")"  'ЗДЕСЬ ЭТА НЕОБНОВЛЯЮЩАЯСЯ ФОРМУЛА!
ActiveSheet.Cells(i + 3, 10).Calculate
ActiveSheet.Cells(i + 3, 10).NumberFormat = "#,##0.00 $"
 
Application.Calculation = xlCalculationManual
Application.Calculation = xlCalculationAutomatic
ActiveSheet.EnableCalculation = True
ThisWorkbook.ActiveSheet.Columns("J:K").Calculate
ActiveWorkbook.RefreshAll
 
       sFiles = Dir
    Loop
    Application.ScreenUpdating = True
End Sub

I am using all the solutions that appear in:

How to refresh ALL cell through VBA

Getting Excel to refresh data on sheet from within VBA

ActiveSheet.EnableCalculation = False  
ActiveSheet.EnableCalculation = True

or

Application.Calculate

or

Application.CalculateFull

None of them works in Excel 2010. When I go to the cell and right click refresh it works. How can I refresh within VBA?

Sheets("Name_of_sheet").Range("D424").Refresh raises an

exception 438

Questions:

  1. How can I make the script support Excel 2003, 2007, 2010?
  2. How can I choose the source file to refresh from using VBA?

EDIT:

  1. I want to simulate a right mouse click and choose refresh in the menu in worksheet 3. That is the entire story.

  2. I work on an Excel file created 10 years ago. When opening in Excel 2010, I can go to a cell and right click on it and choose refresh and then choose the .txt file to refresh from. I am trying to do it automatically within VBA.

Community's user avatar

asked Nov 22, 2012 at 13:39

0x90's user avatar

6

You could try using Application.Calculation

Application.Calculation = xlCalculationManual
Application.Calculation = xlCalculationAutomatic

answered Nov 22, 2012 at 13:42

Anirudh Ramanathan's user avatar

4

For an individual cell you can use:

Range("D13").Calculate

OR

Cells(13, "D").Calculate

0x90's user avatar

0x90

38.9k36 gold badges163 silver badges244 bronze badges

answered Nov 22, 2012 at 13:46

InContext's user avatar

InContextInContext

2,46112 silver badges24 bronze badges

1

I finally used mouse events and keystrokes to do it:

Sheets("worksheet34").Select
Range("D15").Select
Application.WindowState = xlMaximized
SetCursorPos 200, 600 'set mouse position at 200, 600
Call mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0) 'click left mouse
Application.SendKeys ("R")

answered Nov 29, 2012 at 5:52

0x90's user avatar

0x900x90

38.9k36 gold badges163 silver badges244 bronze badges

2

just a reminder;

be careful when using

Application.Calculation = xlCalculationManual
Application.Calculation = xlCalculationAutomatic

this sets the entire excel application to calculate formula’s either automatically or manually. If you use

Application.Calculation = xlCalculationManual

you’ll notice your automatic formulas no longer work.

cheers

answered Feb 16, 2016 at 17:53

LeeF's user avatar

You can force excel to recalculate a cell or range of cells by marking the cell/range as dirty.

Example :

' Recalculate Column D4 to D24
Sheets("Name_of_sheet").Range("D4:D24").Dirty

or

' Recalculate Cell D4<br>
Sheets("Name_of_sheet").Range("D4").Dirty<br>

Ike's user avatar

Ike

7,8904 gold badges11 silver badges29 bronze badges

answered Sep 5, 2021 at 11:16

XYZLOL's user avatar

Application.Calculate didn’t work for my function. Not even when followed by DoEvents.

What I found that works is to re-enter the formula in the cell.
A simple way to get the formula is to start recording a macro, use F2 to edit the cell, then press enter. The macro will make a great copy of the function text with all needed quotes.

Below is an example.

Sheets("Name_of_sheet").Range("D424").FormulaR1C1 = "=now()"

svyat1s's user avatar

svyat1s

8689 gold badges12 silver badges21 bronze badges

answered Mar 5, 2021 at 19:36

Scott's user avatar

Cells(x, y).Select
ActiveCell.FormulaR1C1 = Selection.Value

works perfectly for me

answered Aug 2, 2022 at 20:21

user19260138's user avatar

I have a long «macro» in a workbook > 20 MB, tens of thousands of lines, that calls a dll written in Fortran. None of these methods worked:

Call Application.Calculate
Call Application.CalculateFull
Call Application.CalculateFullRebuild
Re-entering the formula
Range.Dirty

Application.Calculation = xlCalculationManual
Application.Calculation = xlCalculationAutomatic

ThisWorkbook.ActiveSheet.EnableCalculation = False
ThisWorkbook.ActiveSheet.EnableCalculation = True

This worked:

On Error Resume Next
Application.SendKeys "{F2}{Enter}{NumLock}"  'SendKeys turns off NumLock for some reason
On Error GoTo 0

This even worked when a chart was selected.

answered Feb 9 at 14:47

Rocky Scott's user avatar

Rocky ScottRocky Scott

4364 silver badges13 bronze badges

Понравилась статья? Поделить с друзьями:
  • Excel обновить все поля
  • Excel обновить все макросы
  • Excel обновить все запросы
  • Excel обновить все горячая клавиша
  • Excel обмен данными графика