简体   繁体   中英

Excel Sheet Protection Stopping Macro

I have been using a piece of code that zooms to fit the the worksheet to the active window. However, if I add sheet protection the macro will fail. To get around this problem, I call a sub to remove the protection then reapply the protection afterwards. Is there a way to run my sub without removing and reapplying sheet protection?

Code to change zoom:

Sub fixScreenSize()
    Dim rngX As Range
    Dim myLastCell As Range
    Dim myLastCellAdd As String
    Dim rngToZoom As Range      

        'Get address of last cell containing data
        Set myLastCell = Cells(1, 1).SpecialCells(xlLastCell)
            myLastCellAdd = Cells(myLastCell.Row, myLastCell.Column).Address
        'Find keyword in used range
        Set rngX = Range("A1", myLastCellAdd).Find("myZoomRange", lookat:=xlPart)
        'Zoom to correct range
        Range(Cells(1, 1), rngX).Select
        ActiveWindow.Zoom = True
        Range("A1").Select

    Set myLastCell = Nothing
    Set rngX = Nothing
End Sub
  • Remove all sheet protection
  • Open the VBE ( Alt + F11 )
  • Go to the immediate window ( Ctrl + G )
  • Type ActiveSheet.Protect Password:="myPassword", UserInterfaceOnly:=True and press Enter

The active worksheet is now protected with the password "myPassword", however the UserInterfaceOnly argument means that your code is still allowed to run on that sheet unaffected by the sheet's protection

There is no way to do this that I know of without removing and re-adding the protection. Once the protection is set there is no way to get around a sheet protection without removing the protection.

Your way is the correct way and should not impact on performance or anything.

EDIT as it turns out there is a way. However I have always done it this way without problems.

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