Vba excel обновить все данные

ГЛАВНАЯ

ТРЕНИНГИ

   Быстрый старт
   Расширенный Excel
   Мастер Формул
   Прогнозирование
   Визуализация
   Макросы на VBA

КНИГИ

   Готовые решения
   Мастер Формул
   Скульптор данных

ВИДЕОУРОКИ

ПРИЕМЫ

   Бизнес-анализ
   Выпадающие списки
   Даты и время
   Диаграммы
   Диапазоны
   Дубликаты
   Защита данных
   Интернет, email
   Книги, листы
   Макросы
   Сводные таблицы
   Текст
   Форматирование
   Функции
   Всякое
PLEX

   Коротко
   Подробно
   Версии
   Вопрос-Ответ
   Скачать
   Купить

ПРОЕКТЫ

ОНЛАЙН-КУРСЫ

ФОРУМ

   Excel
   Работа
   PLEX

© Николай Павлов, Planetaexcel, 2006-2022
info@planetaexcel.ru


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

Техническая поддержка сайта

ООО «Планета Эксел»

ИНН 7735603520


ОГРН 1147746834949
        ИП Павлов Николай Владимирович
        ИНН 633015842586
        ОГРНИП 310633031600071 

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

«Обновить все» с помощью макроса.Как это сделать,если воможно такое.


Краткость, конечно, сестра таланта, но не в Вашем случае.
«Обновить все» — что все? К какой команде или объекту это относится? _сводные_, диаграммы или еще что?

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…
www.excel-vba.ru
Просто СПАСИБО [+оказать+]
Считаешь СПАСИБО мало? Яндекс.Деньги: 41001332272872; WM: R298726502453


«Обновить все» Ctrl+Alt+F5 Обновление в книге всех сведений из источников данных.Excel 2007 во вклатке «Данные»


Я так полагаю, у Вас сломался макрорекордер? Почему все так брезгуют им пользоваться?

ActiveWorkbook.RefreshAll

Да, вдруг Вы не знаете, что такое макрорекордер — почитайте здесь

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…
www.excel-vba.ru
Просто СПАСИБО [+оказать+]
Считаешь СПАСИБО мало? Яндекс.Деньги: 41001332272872; WM: R298726502453




October 06, 2020/



Chris Newman

Refresh Excel Data Connections VBA

With the release of integrated stock pricing in Microsoft Excel, it was unfortunate there wasn’t any sort of setting that allowed for automatic updating of the stock data while the file was open.

Even worse, there is currently no way to ensure the data refreshes when you initially open your Excel file. This becomes vitally important if you are relying on your stock data to be up-to-date before making any trading decisions.

Let’s look at a few ways we can incorporate VBA code to help remedy the lack of this feature.

In this article, I’ll cover how to:

  • Refresh your query data manually

  • Refresh your data automatically when the file opens

  • Refresh your data automatically when you select a specific tab

  • Refresh your data at a given interval (ie every 30 seconds)

Refresh Data Connections Manually

You can trigger the refreshing of your stock data by either using keyboard shortcut Ctrl+Alt+F5 or navigating to your Excel Ribbon’s Data tab and clicking the Refresh All button within the Queries & Connections button group.

Refresh All Button.png

Refresh Data Connections When File Opens (VBA)

You can trigger a data refresh when your Excel file is first opened by pasting VBA code into the Workbook_Open event. Simply double-click the ThisWorkbook object in the VBA Project Pane to open the text editor (blank white sheet) within the Visual Basic Editor (keyboard shortcut Alt +F11).

Next, paste the below code into the text editor and save.

Private Sub Workbook_Open()
‘PURPOSE: Run Data tab’s Refresh All function when file is opened

ThisWorkbook.RefreshAll

MsgBox «Stock Data has been refreshed!»

End Sub

Workbook Event.png

The next time you open your Excel file, you should see the message box immediately appear indicating that your stock data has been refreshed.

Refresh Data Connections When Sheet Is Activated (VBA)

You can trigger a data refresh when you navigate to a particular spreadsheet tab by pasting VBA code into the Worksheet_Activate event. Simply double-click the desired Sheet object in the VBA Project Pane to open the text editor (blank white sheet) within the Visual Basic Editor (keyboard shortcut Alt +F11). The tab name of your sheets will be inside the parathesis next to the object name, so you can easily decipher which sheet object you want to store the code in.

Next, paste the below code into the text editor and save.

Private Sub Worksheet_Activate()
‘PURPOSE: Run Data tab’s Refresh All function when sheet is activated

ThisWorkbook.RefreshAll

MsgBox «Stock Data has been refreshed!»

End Sub

Worksheet Event.png

The next time you navigate to the particular tab you stored the code in, you should see the message box immediately appear indicating that your stock data has been refreshed.

Refresh Data Connections Every X Seconds (VBA)

Alright, this is for all the day traders out there that want their data automatically refreshed throughout the day. We can utilize VBA’s OnTime functionality to schedule a macro to run and effectively create a loop so that it keeps refreshing at your desired interval.

There are 4 macros in the below code, however, you will only need to call two of them:

  1. StartRefreshLoop — Starts the refresh intervals

  2. EndRefreshLoop — Ends the refresh intervals

You can set the public variable “Seconds” to any interval you wish. Since stock data typically refreshes every 15 minutes, you’ll most likely want to set it to 960 seconds.

Public RefreshTime As Double
Public Const Seconds = 30 ‘Input Refresh Interval in seconds

Sub StartRefreshLoop()

‘User Message indicating loop is beginning
  MsgBox «Refreshes will begin to occur at » & _
    «the designated interval of » & Seconds & » seconds»

‘Call the first Refresh
  Call StartRefreshes

End Sub

Sub StartRefreshes()

‘Calculate Next Refresh Time
  RefreshTime = Now + TimeSerial(0, 0, Seconds)

‘Trigger a Refresh with OnTime function
  Application.OnTime _
    EarliestTime:=RefreshTime, _
    Procedure:=»RefreshConnections», _
    Schedule:=True

  End Sub

Sub RefreshConnections()

‘Refresh Data Connections
  ThisWorkbook.RefreshAll

‘Start Timer Over Again
  Call StartRefreshes

End Sub

Sub EndRefreshLoop()

‘On Error Resume Next
  Application.OnTime _
    EarliestTime:=RefreshTime, _
    Procedure:=»RefreshConnections», _
    Schedule:=False

‘User Message indicating loop has ended
  MsgBox «Refreshes are no longer occurring»

End Sub

I Hope This Helped!

Hopefully, I was able to explain how you can use VBA code to automate refreshing your data connections to ensure you have the most up-to-date stock information in your spreadsheets. If you have any questions about this technique or suggestions on how to improve it, please let me know in the comments section below.

Chris Newman 2020 - TheSpreadsheetGuru

About The Author

Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.

Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you some value today and hope to see you back here soon! — Chris

Skip to content

На чтение 2 мин. Просмотров 8.5k.

Что делает макрос: Это не редкость, когда имеется несколько сводных таблиц в одной книге. Чаще всего эти сводные таблицы ссылаются на данные, которые требует их обновления. Этот макрос поможет обновить все сводные таблицы по первому требованию.

Содержание

  1. Что делает макрос
  2. Код макроса
  3. Как этот код работает
  4. Как использовать

Что делает макрос

Этот макрос — перебирает рабочие листы, а затем перебирает сводные таблицы. На каждом цикле, макрос обновляет сводную таблицу.

Код макроса

Sub ObnovitSvodnieTablici()
'Шаг 1: Объявляем переменные
Dim ws As Worksheet
Dim pt As PivotTable
'Шаг 2: Запускаем цикл через каждый лист книги
For Each ws In ThisWorkbook.Worksheets
'Шаг 3: Запускаем цикл через все сводные таблицы
For Each pt In ws.PivotTables
pt.RefreshTable
Next pt
Next ws
End Sub

Как этот код работает

  1. Шаг 1 первый объявляет объект под названием WS. Это создает контейнер памяти для каждого рабочего листа. Он также объявляет объект под названием PT, который держит
    каждую сводную таблицу.
  2. Шаг 2 просматривает все рабочие листы в этой книге. Обратите внимание, что мы используем ThisWorkbook вместо ActiveWorkbook.
  3. Шаг 3 цикл проходит через все сводные таблицы в каждом листе, а затем запускает RefreshTable метод. После макрос переходит к следующему листу. После того, как все листы были
    оценены, макрос заканчивается. ActiveWorkbook относится к книге, которая в данный момент активна.

В качестве альтернативного метода для обновления всех сводных таблиц в книге, вы можете использовать ThisWorkbook.RefreshAll. Это обновляет все сводные таблицы в рабочей книге. Тем не менее, он также обновляет все таблицы запросов. Так что, если у вас есть таблицы данных, которые подключены к внешнему источнику или в Интернете, на них будет влиять метод RefreshAll. Если это не является проблемой, вы можете просто ввести ThisWorkbook.RefreshAll в стандартный модуль.

Как использовать

Для реализации этого макроса, вы можете скопировать и вставить его в стандартный модуль:

  1. Активируйте редактор Visual Basic, нажав ALT + F11.
  2. Щелкните правой кнопкой мыши имя проекта / рабочей книги в окне проекта.
  3. Выберите Insert➜Module.
  4. Введите или вставьте код.

Понравилась статья? Поделить с друзьями:
  • Vba excel область ячеек
  • Vba excel нумерация строк кода
  • Vba excel нумерация страниц
  • Vba excel номер строки по значению ячейки
  • Vba excel номер строки в диапазоне