使用按钮刷新受保护的数据透视表?

时间:2014-01-29 22:32:01

标签: excel vba excel-vba pivot-table

我有一个按钮来刷新工作表中的所有数据透视表:

Sub Button3_Click()
ThisWorkbook.RefreshAll
End Sub

我想添加功能来刷新所有数据透视表,即使它们位于受保护的工作表上。我使用密码MyPwd保护数据透视表表并使用下面的代码,但它不起作用:

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对我来说都是新手。我做错了什么?

2 个答案:

答案 0 :(得分:1)

您想要的Unprotect是工作表方法。你应该对它进行鉴定。

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

注意TargetShtWith-End With。如果这有帮助,请告诉我们。

修改

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

粘贴到常规模块中,如下所示:

enter image description here

如果有帮助,请告诉我们。

答案 1 :(得分:0)

谢谢你@ BK201对它有所了解,你肯定指出了我正确的方向。我在按钮中使用了这个代码,似乎可以解决这个问题:

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