2017-06-30 69 views
0

我是新來的VBA和我試圖觸發與下面的代碼BeforeRefresh和AfterRefresh事件:BeforeRefresh和AfterRefresh不工作

下名爲clsQuery類模塊,我有:

Option Explicit 
Public WithEvents MyQuery As QueryTable 

Private Sub MyQuery_AfterRefresh(ByVal Success As Boolean) 
If Success Then MsgBox "Query has been refreshed." 
End Sub 

Private Sub MyQuery_BeforeRefresh(Cancel As Boolean) 
If MsgBox("Refresh query?", vbYesNo) = vbNo Then Cancel = True 
End Sub 

然後模塊下,我有:

Option Explicit 
Dim colQueries As New Collection 

Sub InitializeQueries() 

Dim clsQ As clsQuery 
Dim WS As Worksheet 
Dim QT As QueryTable 

For Each WS In ThisWorkbook.Worksheets 
For Each QT In WS.QueryTables 
Set clsQ = New clsQuery 
Set clsQ.MyQuery = QT 
colQueries.Add clsQ 
Next QT 
Next WS 
MsgBox ("Works") 

End Sub 

並且最後在Microsoft Excel對象,我有一個名爲的ThisWorkbook標籤:

Option Explicit 
Dim colQueries As New Collection 

Sub InitializeQueries() 

Dim clsQ As clsQuery 
Dim WS As Worksheet 
Dim QT As QueryTable 

For Each WS In ThisWorkbook.Worksheets 
For Each QT In WS.QueryTables 
Set clsQ = New clsQuery 
Set clsQ.MyQuery = QT 
colQueries.Add clsQ 
Next QT 
Next WS 
MsgBox ("Works") 

End Sub 

所以當我第一次打開excel文件時,messagebox出現並顯示「Works」。但是,當我嘗試刷新數據時,刷新之前和刷新之後的消息框不會出現。任何幫助,將不勝感激!

+0

你重新創建colQueries,這需要進行一次公衆創建,並添加到。我將這個集合公開在一個模塊中,然後在工作表上進行更改,創建新的集合並運行Initialise例程。 –

回答

0

像這樣的東西應該可以幫到你。不太不同,但添加了一個單一的集合。

enter image description here