I need to create an event to apply certain code after data connections (text files) have refreshed. How do i control when the data is refreshed.
-
Either of the answers below helpful for you? It's hard to offer lots of assistance without a very clear problem statement, but perhaps you can try some of the suggestions, and clarify your problem if they're still not working... – David Zemens Mar 31 '16 at 22:16
2 Answers
Turn off background refresh on your connections before you do anything else. Then use ActiveWorkbook.RefreshAll any code placed after will not execute till after the refresh, as long as background refresh is off for all connections.
ActiveWorkbook.RefreshAll
other vba code here

- 488
- 5
- 19
How do i control when the data is refreshed.
Open the Connections menu, and then select the connection, and view/edit its Properties:
I need to create an event to apply certain code after data connections (text files) have refreshed.
I interpreted this literally, as you need an event. Fortunately, it's possible to do this. It's not a built-in event like Worksheet_Change
but it's still something that can be done with VBA.
If you create a class object then a QueryTable object can be configured WithEvents
, and there are two events which you can trap: AfterRefresh
and BeforeRefresh
. Sounds like you need the AfterRefresh
event.
How to add Event Handler for QueryTable
Create a Class module named clsEvents_QueryTable
(or you can name it something else, just be consistent in the rest of the code). Put this code, which will allow you to establish an event-handler for a QueryTable object, and the two events' procedures.
Option Explicit
Public WithEvents cQT As Excel.QueryTable
Private Sub Class_Initialize()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets(1) '## Modify as needed
Set cQT = ws.QueryTables.Item(1) '## Modify as needed
End Sub
Private Sub cQT_AfterRefresh(ByVal Success As Boolean)
'###
' Code placed in, or called *from* this procedrure will run AFTER refresh
MsgBox Me.cQT.Name & " After refreshing..."
End Sub
Private Sub cQT_BeforeRefresh(Cancel As Boolean)
'###
' Code placed in, or called *from* this procedrure will run BEFORE refresh
MsgBox Me.cQT.Name & " Before refreshing..."
End Sub
Put this in the top of a standard module:
Public QT As clsEvents_QueryTable
In your ThisWorkbook
module, do this:
Option Explicit
Private Sub Workbook_Open()
If QT Is Nothing Then
Set QT = New clsEvents_QueryTable
End If
End Sub
(You could do that in some other module, but this is just an example).
Now the table has the two event-handlers, and any time the QueryTable is refreshed, it will automatically invoke the code which is included or called from the event handler(s).
You can extend this to handle multiple QueryTables with some modification (using a collection of object, instead, etc.).

- 1
- 1

- 53,033
- 11
- 81
- 130