A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
Hey Jan
You didn't tell the full story ;-) No prob. to get the Err. 91 with your workbook. And the reason is => your query not only load to your worksheet (Einsatz_G) but also to the Data Model
In such case we don't refresh a ListObject.QueryTable but a ListObject.TableObject. And given what you want to acheive re. unprotecting before and reprotecting after the refresh this makes life easier.
The TableObject.Refresh method as no property at all (so nothing like BackgroundQuery) and the good Reason for that is when you Add your query result to the data model, the Background refresh capability is automatically disable
You can check this as follow: Click on your pq_unikate_GUV table > Go to Data tab > under Refresh All > Connection Properties:
Code successfully tested in your workbook (as well as mine where the query takes much more time to refresh when Table100K) is select
Option Explicit
Sub RefreshTableObject()
'
Dim thisSubName As String: thisSubName = "RefreshTableObject"
Dim myTableObjName As String: myTableObjName = "pq_unikate_GUV"
Dim wSheet As Worksheet
Dim PowerPivTable As TableObject
Dim msgRefreshing As String
On Error GoTo ERR_HANDLER
Set wSheet = ThisWorkbook.Worksheets(GetSheetWithOl(myTableObjName))
Call EnableEvents(False)
msgRefreshing = "Refreshing query " & myTableObjName & "..."
With wSheet
Set PowerPivTable = .ListObjects(myTableObjName).TableObject
'.Activate ' not required
.Unprotect
Application.StatusBar = msgRefreshing
PowerPivTable.Refresh
.Protect
End With
ERR_HANDLER_EXIT:
'
Application.StatusBar = ""
Call EnableEvents(True)
Exit Sub
ERR_HANDLER:
'
MsgBox "Error " & Err.Number & ": " & Err.Description & vbLf _
& "occured in Sub " & thisSubName, vbCritical
Resume ERR_HANDLER_EXIT
End Sub
Sub EnableEvents(ByVal Toggle As Boolean)
'
With Application
If Toggle Then
.EnableEvents = True
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
Else
.EnableEvents = False
.ScreenUpdating = False
.Calculation = xlCalculationManual
.DisplayStatusBar = True
End If
End With
End Sub
Private Function GetSheetWithOl(ByVal loName As String) As String
'
Dim wBook As Workbook
Dim wSheet As Worksheet
Dim oList As ListObject
Set wBook = ThisWorkbook
For Each wSheet In wBook.Worksheets
For Each oList In wSheet.ListObjects
If oList.Name = loName Then
GetSheetWithOl = wSheet.Name
Exit Function
End If
Next oList
Next wSheet
End Function
You owe me a Weißbier for the incomplete story ;-)
Before closing with Mark as Answer it would make sense you revise the title of your thread so it better reflects the case (can help others with similar scenario). Something like => VBA Refresh query loaded to Data Model and re-protect sheet