简体   繁体   中英

How to auto-protect individual worksheets in Excel using VBA?

I've put this code into a worksheet which should make sure individual worksheets are protected with their individual passwords. It seems to work fine but I'm trying to access the worksheets and all of them are saying incorrect password?

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    With ThisWorkbook
        .Worksheets("2073 NSW").Protect Password = "2073"
        .Worksheets("2091 NSW").Protect Password = "2091"
        .Worksheets("3105 VIC").Protect Password = "3105"
        .Worksheets("3091 VIC").Protect Password = "3091"
        .Worksheets("4058 QLD").Protect Password = "4058"
        .Worksheets("4091 QLD").Protect Password = "4091"
        .Worksheets("6024 WA").Protect Password = "6024"
        .Worksheets("6091 WA").Protect Password = "6091"
    End With
    Application.EnableAnimations = False
    ThisWorkbook.Save
    Application.EnableEvents = True
End Sub

The problem is inside the With ThisWorkbook line. It should be Password:="2073" not Password = "2073"
You forgot to use the := which used to assign a value to a certain named argument.

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    With ThisWorkbook
        .Sheets("2073 NSW").Protect Password:="2073"
        .Sheets("2091 NSW").Protect Password:="2091"
        .Sheets("3105 VIC").Protect Password:="3105"
        .Sheets("3091 VIC").Protect Password:="3091"
        .Sheets("4058 QLD").Protect Password:="4058"
        .Sheets("4091 QLD").Protect Password:="4091"
        .Sheets("6024 WA").Protect Password:="6024"
        .Sheets("6091 WA").Protect Password:="6091"
    End With
    Application.EnableAnimations = False
    ThisWorkbook.Save
    Application.EnableEvents = True
End Sub

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