简体   繁体   中英

Refresh protected pivot-table with a button?

I have this macro for a button to refresh all the pivot-tables in a worksheet:

Sub Button3_Click()
ThisWorkbook.RefreshAll
End Sub

And I wanted to add the functionality to refresh all the pivot tables even if they are on a protected sheet. I protected the pivot-table sheet with the password MyPwd and used the below code, but it won't work:

Sub Button3_Click()
Unprotect Password:="MyPwd"
ThisWorkbook.RefreshAll
Protect Password:="MyPwd", _
DrawingObjects:=True, Contents:=True, _
Scenarios:=True, AllowUsingPivotTables:=True
End With
End Sub

Visual Basic is all new to me. What am I doing wrong?

The Unprotect you want is a worksheet method. You should qualify it.

Sub ProtRef()
    Dim TargetSht As Worksheet
    Set TargetSht = ThisWorkbook.Sheets("Sheet1") 'Modify as needed.

    With TargetSht
        .Unprotect MyPwd
        ThisWorkbook.RefreshAll
        .Protect MyPwd
    End With
End Sub

Note TargetSht and the With-End With . Let us know if this helps.

EDIT:

Sub ProtRef()

    Dim WB As Workbook, WS As Worksheet

    For Each WS In WB.Worksheets
        If WS.Name <> "Sheet1" Then
            WS.Unprotect MyPwd
        End If
    End With

    ThisWorkbook.RefreshAll

    For Each WS In WB.Worksheets
        If WS.Name <> "Sheet1" Then
            WS.Protect MyPwd
        End If
    End With

End Sub

Paste in a regular module, like below:

在此处输入图片说明

Let us know if this helps.

Thank you @BK201 for having a crack at it, you definitely pointed me in the right direction. I used this code in the button and it seemed to do the trick:

Sub Button1_Click()


Dim Sht As Worksheet

For Each Sht In ThisWorkbook.Worksheets
Sht.Unprotect Password:="MyPwd"
ThisWorkbook.RefreshAll

Next

For Each Sht In ThisWorkbook.Worksheets
Sht.Protect Password:="MyPwd"
Next

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM