If you want a specific error handling, then this is what I recommend:
Sub RefreshConnectionsWithErrorHandler()
Dim cn As WorkbookConnection
Dim isPowerQueryConnection As Boolean
Dim errMsg As String
On Error GoTo ErrorHandler ' Enable error handling for the entire sub
' Loop through all connections
For Each cn In ActiveWorkbook.Connections
isPowerQueryConnection = InStr(1, cn.OLEDBConnection.Connection, "Provider=Microsoft.Mashup.OleDb.1") > 0
' Refresh each connection
If isPowerQueryConnection Then
cn.OLEDBConnection.BackgroundQuery = False ' Disable background refresh for better error visibility
On Error Resume Next ' temporarily ignore errors within the single connection refresh
cn.Refresh
On Error GoTo ErrorHandler ' re-enable normal error handling
' Check for an error condition by checking if the connection was successfully refreshed.
If Err.Number <> 0 Then
errMsg = "Error refreshing connection '" & cn.Name & "': " & Err.Description
Debug.Print errMsg
Else
Debug.Print "Connection '" & cn.Name & "' refreshed successfully."
End If
Err.Clear ' Clear the error, so you do not get the same error for multiple connections.
Else
Debug.Print "Skipping non Power Query connection: " & cn.Name
End If
Next cn
MsgBox "All connections processed. Check the Immediate Window for details.", vbInformation
Exit Sub
ErrorHandler:
' Handle general errors
MsgBox "An unexpected error occurred during refresh. Error: " & Err.Description, vbCritical
End Sub
The code iterates through each connection in the active workbook using For Each cn In ActiveWorkbook.Connections
.
It checks for a Power Query connection using a substring search within the connection string.
cn.OLEDBConnection.BackgroundQuery = False
is set before refreshing for better error handling.
The ErrorHandler
catches any unexpected errors and displays a message box.
Error Checking and Handling:
The Err.Number
is evaluated after each attempted refresh.
If Err.Number
is not 0, an error message and the connection name are printed to the Immediate Window.
If no error occurs, a success message is printed to the Immediate Window.
The Err.Clear
statement clears the error, preventing the same error from being reported multiple times.