This is my reference to Before/After Query Refresh Event
To import data from SQL Server, I have a parameterized query that requires for a date input from the user.
When the user enters the beginning date and end date correctly, everything is completed in the correct order, and the case is closed.
However, when the date is not correct, the error handler is not triggered, and the macro continues until the AfterRefresh event.
I added error handlers to every module, but they are still not responding. Does anyone know how to add an error handler to a Before/After Refresh Event?
The logic of the power query code is as follows, but not written in this manner:
let
Source = Sql.Database("MyDataBase", [Query="Select Transaction_date, Customer_ID
from TransactionList
where Transaction_date between @StartDate and @EndDate]
in
Source
VBA Code below
'========== [ Modules ] ==========
Option Explicit
Dim colQueries As New Collection
Sub Button_RefreshData()
On Error GoTo Error_Handler
Call InitializeQueries
ThisWorkbook.RefreshAll
Exit Sub
Error_Handler:
MsgBox Err.Number & " " & Err.Source & vbNewLine & Err.Description, vbInformation
Exit Sub
End Sub
Sub InitializeQueries()
On Error GoTo Error_Handler
Dim clsQ As clsQuery
Dim WS As Worksheet
Dim QT As QueryTable
Dim LO As ListObject
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
For Each LO In WS.ListObjects
Set QT = LO.QueryTable
Set clsQ = New clsQuery
Set clsQ.MyQuery = QT
colQueries.Add clsQ
Next LO
Next WS
Exit Sub
Error_Handler:
MsgBox Err.Number & " " & Err.Source & vbNewLine & Err.Description, vbInformation
Exit Sub
End Sub
'========== [ Class Modules named clsQuery ] ==========
Option Explicit
Public WithEvents MyQuery As QueryTable
Private Sub MyQuery_AfterRefresh (ByVal Success As Boolean)
On Error GoTo Error_Handler
If Success Then MsgBox ("The entire process is complete.")
Exit Sub
Error_Handler:
MsgBox Err.Number & " " & Err.Source & vbNewLine & Err.Description, vbInformation
Exit Sub
End Sub
Private Sub MyQuery_BeforeRefresh (Cancel As Boolean)
On Error GoTo Error_Handler
MsgBox ("The process start now.")
Exit Sub
Error_Handler:
MsgBox Err.Number & " " & Err.Source & vbNewLine & Err.Description, vbInformation
Exit Sub
End Sub
Exit Suband before theEnd Sub. I'm don't think that will stop yourOn Error Gotoline from working, but it will try and display an error message at the end of every procedure whether an error occurred or not.Sub demo() On Error GoTo X ThisWorkbook.RefreshAll Exit Sub X: MsgBox "never gets here" End Sub