Link to home
Start Free TrialLog in
Avatar of hindersaliva
hindersalivaFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Excel 2013 VBA - updating Power Query on a protected

The code below works fine if it’s stepped through using F8. The purpose is to

Unprotect a sheet
Update a power query query
Reprotect the sheet

However, when assigned to a button, I get an error: 'cannot make changes to a protected sheet'.

Public Sub UpdatePowerQueries()
    ' Macro to update my Power Query script(s)
    
    Dim cn As WorkbookConnection
    
    ActiveSheet.Unprotect Password:="ecart"
    
    For Each cn In ThisWorkbook.Connections
        If cn = "Power Query - Query1" Then cn.Refresh
    Next cn
        
    With ActiveSheet
       .Protect Password:="ecart", AllowFiltering:=True, AllowSorting:=True, DrawingObjects:=True _
        , Contents:=True, Scenarios:=True, AllowUsingPivotTables:=True, UserInterfaceOnly:=True

    End With
     
End Sub

Open in new window

Avatar of Rgonzo1971
Rgonzo1971

Hi,

Is the activesheet always the one with the connection

Regards
Avatar of hindersaliva

ASKER

Rgonzo, yes.

Query1 is also the only query in the workbook
ASKER CERTIFIED SOLUTION
Avatar of Rgonzo1971
Rgonzo1971

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The problem was caused by Background Refresh.