Why aren't these columns locking properly?

Viewed 45

I have to protect columns A:O from being edited in a worksheet I'm creating, but it doesn't seem to be working properly.

 Set Wb = Workbooks.Add(XlWBATemplate.xlWBATWorksheet)
        With Wb
        With .Worksheets("Sheet1")
             .Cells.Locked = False
             .Columns("A:O").Locked = True  
        End With

Why are those columns able to be edited after I run the macro?

Rest of script underneath (including saving):

 .SaveAs strNewPath & strFileName, Password:="password", FileFormat:=51
            .Saved = True
            .Close

        End With
        Set Wb = Nothing
    End If
Next
2 Answers

I'll just add on with an answer to clarify things. The Locked property simply indicates whether or not the cells is modifiable when the sheet is protected. You can protect a sheet by going to the Review tab in the Excel toolbar, then selecting Protect Sheet.

Alternatively, you can protect and unprotect within your code. For example:

Sub Protect_Sheet()
    Sheet1.Protect "Password"
End Sub

Sub Unprotect_Sheet()
    Sheet1.Unprotect "Password"
End Sub

You can call these methods within a larger method if you want to perfrom some action on locked sheets, then protect the sheet.

When the code start import:

Sheet1.Unprotect "Password" '<- Unprotect the sheet in order to Unlock sheet and give the opportunity to the code to work.

and when the code finish import:

Sheet1.Protect "Password" '<- Protect the sheet in order to lock the sheet 
Related