In VBA (Visual Basic for Applications), “Lock & Unlock” usually refers to one of three different things depending on your specific goals: controlling cell editing in Excel workbooks, protecting your macro source code from being viewed, or managing multi-user text/binary file access. 1. Locking and Unlocking Excel Cells & Sheets
By default, all cells in an Excel worksheet have their .Locked property set to True. However, this locking behavior only takes effect after the sheet is protected.
To protect specific cells while leaving others open for data entry, you must flip the properties using VBA.
Sub LockAndProtect() Dim ws As Worksheet Set ws = ThisWorkbook.Sheets(“Sheet1”) ‘ 1. Unprotect the sheet first to make structural changes ws.Unprotect Password:=“MyPassword” ’ 2. Unlock the entry range (e.g., A1:B10) ws.Range(“A1:B10”).Locked = False ‘ 3. Lock a restricted range (e.g., C1:C10) ws.Range(“C1:C10”).Locked = True ’ 4. Re-protect the sheet to activate the locks ws.Protect Password:=“MyPassword” End Sub Use code with caution. The UserInterfaceOnly Pro-Tip
If your macro needs to edit locked cells without constantly unlocking and re-locking the sheet (which slows down performance), use the UserInterfaceOnly argument. This protects the sheet from human users but leaves it wide open for your VBA code: ws.Protect Password:=“MyPassword”, UserInterfaceOnly:=True Use code with caution. 2. Locking and Unlocking the VBA Project (Source Code)
If you build a tool and want to prevent users from viewing, editing, or deleting your macros, you can lock the VBA project container itself. Операторы Lock, Unlock (VBA) – Microsoft Learn
Leave a Reply