October 06, 2020/
Chris Newman
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 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
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
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:
-
StartRefreshLoop — Starts the refresh intervals
-
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.
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
Happy Monday!, and it is Macro Time. Welcome to another #MacroMonday #Excel blog posts in my 2020 series. Today we will write a simple macro to refresh all data connections when your Excel workbook is opened.
Excel Data Sources.
External Data sources could be MS Query connections, Pivot Table connections or Web Queries. If you take a look at the Data Tab in the Connections Group you will see available data sources. Depending on your version of Excel, this may look slightly different,
What Does The Macro Do?
This macro will automatically refresh ANY data connections when you open your Excel workbook.
Preparing To Write The Macro Using ThisWorkbook Open Event.
First, you will need to open the Visual Basic Editor. There are two ways to do this.
- Either by hitting ALT +F11.
- or selecting the Developer Tab | Code Group | Visual Basic. Both methods have the same result.
The macro uses the ThisWorkbook Open event, which points to the current workbook. This is slightly different to the ActiveWorkbook in that ThisWorkbook is the workbook that contains the code as opposed to the ActiveWorkbook which is any workbook that is currently active. See the difference?. The Syntax of the ThisWorkbook Open event is as follows
expression.Open
expression An expression that returns a Workbook object.
Starting The Macro.
As this code deals with a worksheet opening event, then it makes sense that the code needs to be not in a module as in a lot of VBA code, but within the code of the workbook itself. To enter the code into the relevant worksheet:
- Simply double click on ThisWorkbook in the VB Project Explorer.
- In the left-hand drop-down box select Worksheet
- In the right-hand drop-down box select Open
Excel starts the code off for us, and also enters the End Sub command at this stage too. All we need to do is write the rest of the code between these two lines.
[stextbox id=’info’]
Private Sub Workbook_Open()
End Sub
[/stextbox]
Refresh All Data Connections.
Next, we use a simple one line of code that uses the RefreshAll method to refresh all of the connections that are contained within your workbook or worksheet. If you have numerous connections or Pivot Tables then this will automatically refresh them all.
[stextbox id=’info’]
Workbooks(ThisWorkbook.Name).RefreshAll
[/stextbox]
We would not want to refresh connections in other workbooks, hence we use ThisWorkbook object. Ok so let’s get on and get this coding done and test it. That is my favourite part of writing this macro. This is a really great way to refresh all data connections in your Excel workbook.
If you want more tips then sign up to my monthly Newsletter where I share 3 Excel Tips on the first Wednesday of the month and receive my free Ebook, 30 Excel Tips.
Likewise, if you want to see all of the blog posts in the Macro Mondays Series Click The Link Below
How To Excel At Excel – Macro Mondays Blog Posts.
I’m trying to loop through each connection in my Excel workbook and refresh each one individually and capture any error messages in between each refresh. However, I receive a ‘Type-Mismatch’ error when trying to run the code:
Private Sub btnRefreshConns_Click()
Dim cn As WorkbookConnection
Set cn = ActiveWorkbook.Connections.Count
For Each cn In Workbook.Connections
cn.Refresh
Next
End Sub
Could someone please assist me?
pnuts
58k11 gold badges85 silver badges137 bronze badges
asked Sep 7, 2015 at 10:09
Private Sub btnRefreshConns_Click()
Dim cn As WorkbookConnection
'Remove this line --> Set cn = ActiveWorkbook.Connections.Count
For Each cn In ActiveWorkbook.Connections
cn.Refresh
Next
End Sub
should do it. With For Each
, you don’t need to keep track of the count.
(Note: apostrophes '
introduce comments in VB, so you can try commenting out offending lines to see what happens.)
edit: The loop needs to refer to ActiveWorkbook
. Workbook
is a type, i.e., what kind of thing ActiveWorkbook
is. ActiveWorkbook
is an object, an actual thing you can manipulate.
answered Sep 7, 2015 at 10:16
cxwcxw
16.6k2 gold badges45 silver badges80 bronze badges
4
Содержание
- Метод OLEDBConnection.Refresh (Excel)
- Синтаксис
- Замечания
- Поддержка и обратная связь
- An Excel Blog For The Real World
- Refresh All Data Connections/Queries In Excel
- Refresh Data Connections Manually
- Refresh Data Connections When File Opens (VBA)
- Refresh Data Connections When Sheet Is Activated (VBA)
- Refresh Data Connections Every X Seconds (VBA)
- I Hope This Helped!
- About The Author
- How to Refresh Data Connections in Excel VBA
- Refresh Data Connections Manually
- Refresh Data Connections When File Opens (VBA)
- Refresh Data Connections When Sheet Is Activated (VBA)
- Refresh Data Connections Every X Seconds (VBA)
- Метод ODBCConnection.Refresh (Excel)
- Синтаксис
- Замечания
- Поддержка и обратная связь
Метод OLEDBConnection.Refresh (Excel)
Обновляет подключение OLE DB.
Синтаксис
выражение.Refresh
Выражение Переменная, представляющая объект OLEDBConnection .
Замечания
При подключении к источнику данных OLE DB Microsoft Excel использует строку подключения, указанную свойством Connection . Если в указанной строке подключения отсутствуют необходимые значения, будут отображаться диалоговые окна с запросом у пользователя необходимых сведений. Если свойство DisplayAlerts имеет значение False, диалоговые окна не отображаются, а метод Refresh завершается ошибкой с исключением недостаточных сведений о подключении.
После успешного подключения Microsoft Excel сохраняет завершенную строку подключения, чтобы не отображались запросы для последующих вызовов метода Refresh во время того же сеанса редактирования. Вы можете получить завершенную строку подключения, изучив значение свойства Connection .
После подключения к базе данных выполняется проверка SQL-запроса. Если запрос недопустим, метод Refresh завершается ошибкой с исключением ошибки синтаксиса SQL.
Метод Refresh возвращает значение True , если запрос успешно завершен или запущен; возвращает значение False , если пользователь отменяет подключение.
Чтобы узнать, превышает ли количество извлекаемых строк количество доступных строк на листе, изучите свойство FetchedRowOverflow . Это свойство инициализируется при каждом вызове метода Refresh .
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
An Excel Blog For The Real World
A blog focused primarily on Microsoft Excel, PowerPoint, & Word with articles aimed to take your data analysis and spreadsheet skills to the next level. Learn anything from creating dashboards to automating tasks with VBA code!
Refresh All Data Connections/Queries In Excel
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 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 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
MsgBox «Stock Data has been refreshed!»
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
MsgBox «Stock Data has been refreshed!»
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:
StartRefreshLoop — Starts the refresh intervals
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
‘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
‘Calculate Next Refresh Time
RefreshTime = Now + TimeSerial(0, 0, Seconds)
‘Trigger a Refresh with OnTime function
Application.OnTime _
EarliestTime:=RefreshTime, _
Procedure:=»RefreshConnections», _
Schedule:= True
‘Refresh Data Connections
ThisWorkbook.RefreshAll
‘Start Timer Over Again
Call StartRefreshes
‘On Error Resume Next
Application.OnTime _
EarliestTime:=RefreshTime, _
Procedure:=»RefreshConnections», _
Schedule:= False
‘User Message indicating loop has ended
MsgBox «Refreshes are no longer occurring»
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.
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
Источник
How to Refresh Data Connections in Excel VBA
The first one will “refresh” only one file. The second will “refresh” all open excel files.
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.
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 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
MsgBox “Stock Data has been refreshed!”
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
MsgBox “Stock Data has been refreshed!”
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:
- StartRefreshLoop – Starts the refresh intervals
- 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
‘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
‘Calculate Next Refresh Time
RefreshTime = Now + TimeSerial(0, 0, Seconds)
‘Trigger a Refresh with OnTime function
Application.OnTime _
EarliestTime:=RefreshTime, _
Procedure:=”RefreshConnections”, _
Schedule:=True
‘Refresh Data Connections
ThisWorkbook.RefreshAll
‘Start Timer Over Again
Call StartRefreshes
‘On Error Resume Next
Application.OnTime _
EarliestTime:=RefreshTime, _
Procedure:=”RefreshConnections”, _
Schedule:=False
‘User Message indicating loop has ended
MsgBox “Refreshes are no longer occurring”
Источник
Метод ODBCConnection.Refresh (Excel)
Обновляет подключение ODBC.
Синтаксис
выражение.Refresh
Выражение Переменная, представляющая объект ODBCConnection .
Замечания
При подключении к источнику данных ODBC Microsoft Excel использует строку подключения, указанную свойством Connection . Если в указанной строке подключения отсутствуют необходимые значения, будут отображаться диалоговые окна с запросом у пользователя необходимых сведений. Если свойство DisplayAlerts имеет значение False, диалоговые окна не отображаются, а метод Refresh завершается ошибкой с исключением недостаточных сведений о подключении.
После успешного подключения Excel сохраняет завершенную строку подключения, чтобы не отображались запросы для последующих вызовов метода Refresh во время того же сеанса редактирования. Вы можете получить завершенную строку подключения, изучив значение свойства Connection .
После подключения к базе данных выполняется проверка SQL-запроса. Если запрос недопустим, метод Refresh завершается ошибкой с исключением ошибки синтаксиса SQL.
Если запрос требует параметров, перед вызовом метода Refresh коллекция Parameters должна быть инициализирована с помощью сведений о привязке параметров. Если не достаточно параметров было привязано, метод Refresh завершается ошибкой с исключением ошибка параметра. Если для параметров задан запрос их значений, для пользователя отображаются диалоговые окна независимо от значения свойства DisplayAlerts . Если пользователь отменяет диалоговое окно параметров, метод Refresh останавливается и возвращает значение False. Если дополнительные параметры связаны с коллекцией Parameters , эти дополнительные параметры игнорируются.
Метод Refresh возвращает значение True , если запрос успешно завершен или запущен; Возвращает значение False , если пользователь отменяет подключение или диалоговое окно параметров.
Чтобы узнать, превышает ли количество извлекаемых строк количество доступных строк на листе, изучите свойство FetchedRowOverflow . Это свойство инициализируется при каждом вызове метода Refresh .
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Vsevolod Пользователь Сообщений: 485 |
#1 14.07.2018 08:14:59 Привет
|
||
Андрей VG Пользователь Сообщений: 11878 Excel 2016, 365 |
#2 14.07.2018 09:59:59 Доброе время суток
Вдруг, да поможет. А то вы отключаете фоновое обновление у одного объекта, а метод обновления запускаете для более высокоуровневого. Проверить не могу. Дома нет таких наборов данных, чтобы оценить. |
||
Vsevolod Пользователь Сообщений: 485 |
#3 14.07.2018 16:22:57 Андрей VG, Спасибо за помощь! Попробовал — стартует один коннект, потом к нему через какое-то время второй добавляется. А хочется, чтобы они шли поочередно. Тут обсуждали.
|
||
Андрей VG Пользователь Сообщений: 11878 Excel 2016, 365 |
#4 14.07.2018 16:40:39
Тогда костыль, навроде
|
||||
Vsevolod Пользователь Сообщений: 485 |
Андрей VG, по исследую еще и отпишусь. Мне кажется кружок крутиться — НО Excel понимает, что все данные он уже собрал и рендерит(мои догадки) и стартует следующее обновление. Так как в других моделях когда много коннектов больше задержки. Отпишусь по результату! Благодарю за помощь! |
PooHkrd Пользователь Сообщений: 6602 Excel x64 О365 / 2016 / Online / Power BI |
Vsevolod, вы можете все таки объяснить зачем вы выдергиваете данные в таблицу на лист, а затем обращаетесь другими запросами к этой таблице, вместо того чтобы закинуть результат первого запроса в буфер и другими запросами обращаться к уже готовой таблице в памяти? Изменено: PooHkrd — 16.07.2018 09:34:57 Вот горшок пустой, он предмет простой… |
TheBestOfTheBest Пользователь Сообщений: 2366 Excel 2010 +PLEX +SaveToDB +PowerQuery |
#7 16.07.2018 12:09:18
Есть ощущение, что цепочка запросов в PQ всегда пересчитывается при изменении первого, причем очередность он «знает сам». Первым может быть и 7-й в списке из 10-ти. Тогда 7, 8, 9 и 10-й пересчитаются автоматически. И это никак не изменить, даже в 2016-м. Неизлечимых болезней нет, есть неизлечимые люди. |
||
Vsevolod Пользователь Сообщений: 485 |
#8 18.07.2018 11:33:10 Андрей VG, спасибо большое! Не могу сообразить, как переменную, что туда передать?
Пробовал такие два варианта:( |
||
PooHkrd Пользователь Сообщений: 6602 Excel x64 О365 / 2016 / Online / Power BI |
Т.е. у вас на выходе несколько одновременно выполняемых запросов, каждый из которых выводит данные в какие-то таблицы? Если так, то да, создаются параллельные цепочки, которые выполняются одновременно. Вот горшок пустой, он предмет простой… |
Vsevolod Пользователь Сообщений: 485 |
#10 19.07.2018 17:43:17 Андрей VG, смог сделать по примеру, как показал Андрей. |