简体   繁体   English

Excel宏数据刷新和保护

[英]Excel macro data refresh and protection

In an Excel macro I need to unprotect a sheet, refresh the data and then protect the sheet. 在Excel宏中,我需要取消保护工作表,刷新数据,然后保护工作表。 The following works: 以下作品:

Dim rs As Worksheet
For Each rs In Worksheets
    rs.Unprotect Password:="SomePassword"
Next rs
ActiveWorkbook.RefreshAll

This does not: 这不是:

Dim rs As Worksheet
For Each rs In Worksheets
    rs.Unprotect Password:="SomePassword"
Next rs
ActiveWorkbook.RefreshAll
For Each rs In Worksheets
    rs.Protect Password:="SomePassword"
Next rs

Produces the following error: 产生以下错误:

The cell or chart you are trying to change is protected and therefore read-only. 您尝试更改的单元格或图表受到保护,因此为只读。

I've tried MANY methods to delay the continuing of the macro until the refresh is finished but nothing has worked. 我尝试了许多方法来延迟宏的继续,直到刷新完成,但没有任何效果。 I've looked at methods on this forum and found none that work. 我在该论坛上查看了方法,但没有找到有效的方法。 What will work? 有什么用?

Try one of the following: 请尝试以下方法之一:

  1. Add DoEvents after ActiveWorkbook.RefreshAll . ActiveWorkbook.RefreshAll之后添加DoEvents Like this: 像这样:

     Dim rs As Worksheet For Each rs In Worksheets rs.Unprotect Password:="SomePassword" Next rs ActiveWorkbook.RefreshAll: DoEvents For Each rs In Worksheets rs.Protect Password:="SomePassword" Next 
  2. Set UserInterfaceOnly argument to true when protecting the workbook. 保护工作簿时,将UserInterfaceOnly参数设置为true。 Something like: 就像是:

     rs.Protect Password:="SomePassword", UserInterfaceOnly:=True 

I get the same error message with the following sub, I have noticed that the error message refers to worksheets containing pivot tables: 我在以下子代码中得到了相同的错误消息,我注意到该错误消息引用了包含数据透视表的工作表:

Private Sub Refresh()
Dim wks As Worksheet
For Each wks In ThisWorkbook.Worksheets
    wks.Unprotect
Next wks
ThisWorkbook.RefreshAll: DoEvents
For Each wks In ThisWorkbook.Worksheets
    wks.Protect UserInterfaceOnly:=True
Next wks
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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