Excel VBA - After Data Import [duplicate]

送分小仙女□ 提交于 2019-12-18 07:24:24

问题


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.


回答1:


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



回答2:


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.).



来源:https://stackoverflow.com/questions/36341741/excel-vba-after-data-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!