简体   繁体   中英

Excel 365 vba - (un)protect sheet slows down macro a lot

Unprotecting/protecting a sheet using VBA is much slower in Excel 365 compared to Excel 2007. Does anyone have the slightest idea as to why this is the case? And is there anything that can be done to resolve this without just omitting the protect-functions?

To make sure the issue is caused solely by the unprotect/protect statements, I tested with a blank workbook containing a single module with the following code:

Dim secondsElapsed As Double

startTime = Timer
Sheets("test").Unprotect ("****")
ThisWorkbook.Sheets("Timers").Cells(1, 1) = Round(Timer - startTime, 2)

startTime = Timer
Sheets("test").Protect Password:="****", DrawingObjects:=False, Contents:=True, Scenarios:=True, AllowSorting:=True, AllowFiltering:=True
ThisWorkbook.Sheets("Timers").Cells(2, 1) = Round(Timer - startTime, 2)

`

This yields the following averages:

  • Excel 2007
    • unprotect: 0.02 seconds
    • protect: 0.01 seconds
  • Excel 365
    • unprotect: 0.52 seconds
    • protect: 0.47 seconds

After more research and asking on other forums, I have found a solution. It is possible to protect only for the user, and thus not for VBA, by adding the UserInterfaceOnly:=True parameter in the protect statement. Therefore, it is merely necessary to protect once (ie the (un)protect statements in the rest of the code can be omitted).

Of course, this does not yet explain why the (un)protect statements take this long. To try to find an answer tot this problem, I will contact Microsoft directly.

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