首页 > 解决方案 > 刷新受保护工作表上的数据透视 - 即使在 VBA 中取消保护也会出错

问题描述

我有一个数据透视表,它会在工作表激活时自动刷新,其中包含来自另一个受保护选项卡的数据。即使我在刷新之前取消保护选项卡,我仍然得到:

Run-time error '1004':
Cannot edit PivotTable on protected sheet.

我的 VBA:

Private Sub Worksheet_Activate()
   Sheets("Extract").Unprotect "password"
   ActiveSheet.PivotTables("pvt_Activity").PivotCache.Refresh
   Sheets("Extract").Protect Password:="password", Contents:=True, Scenarios:=True
End Sub

把我的头撞在墙上 - 为什么这不起作用?

干杯

标签: excelvbapivot-table

解决方案


由于数据透视表位于受保护的工作表中,因此您会收到此错误,因此您需要在刷新之前取消保护它们

所以在每张纸上都有一个刷新按钮并在下面分配这个宏,

g_sPassword->是取消保护工作表的密码,我已经声明为变量,所以我直接使用它

子 RefreshPtInFirstsheet()

Call RefreshPivotTables(sheetname1)

结束子

子 RefreshPtInSecondsheet()

Call RefreshPivotTables(sheetname2)

结束子

子刷新数据透视表(sht 作为工作表)

Dim pt As pivotTable

sheetname1.Unprotect g_sPassword
sheetname2.Unprotect g_sPassword
For Each pt In sht.PivotTables
    pt.PivotCache.Refresh
    Exit For
Next pt
sheetname1.Protect g_sPassword
sheetname2.Protect g_sPassword
MsgBox "Pivot Table Updated"

结束子


推荐阅读