You can't directly unlock a worksheet within a macro. Worksheets in Excel are locked to prevent accidental changes, but macros themselves are not locked. If you need to make changes to a locked worksheet from within a macro, you'll need to temporarily unlock the worksheet, make your changes, and then re-lock it.
Here's how you can do this using VBA code:
-
Unlock the Worksheet:
Sheets("Sheet1").Protect UserInterfaceOnly:=True 'Unlocks the sheet for editing
This code unlocks the sheet named "Sheet1". Replace "Sheet1" with the actual name of the sheet you want to unlock. The
UserInterfaceOnly:=True
argument ensures that the sheet is unlocked only for editing through VBA, not for manual changes through the user interface. -
Make Your Changes:
After unlocking the sheet, you can make any changes you need, such as adding, deleting, or modifying data.
-
Re-lock the Worksheet:
Sheets("Sheet1").Protect Password:="MyPassword" 'Re-locks the sheet
This code re-locks the sheet with the password "MyPassword." Replace "MyPassword" with your desired password.
Example:
Let's say you want to add a new row to a locked worksheet named "Data" using a macro:
Sub AddRowToLockedSheet()
Sheets("Data").Protect UserInterfaceOnly:=True 'Unlock the sheet
'Add a new row
Rows("2:2").Insert Shift:=xlDown
Sheets("Data").Protect Password:="MyPassword" 'Re-lock the sheet
End Sub
This macro will unlock the "Data" sheet, insert a new row below the first row, and then re-lock the sheet with the password "MyPassword."
Important Considerations:
- Password Protection: If the worksheet is password protected, you'll need to use the
Password
argument when unlocking and re-locking the sheet. - User Interface Protection: If the worksheet is protected for user interface only, you can unlock it for editing without using a password.
- Security: Be cautious when working with protected worksheets. Ensure you have a valid password and consider using strong passwords to protect sensitive information.