Discussion Locked

Locking a cell

0 helpful
4 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.
In Excel I was wondering if anyone knew of a way to make an IF Function locka a cell using a criteria. This would help out a great deal.

4 replies

by firstpeter

Yes...but.

The "Yes":
Open your workbook. Press CTRL-F11 (Visual Basic Editor). On the left side in the Project Explorer you'll see your workbook with branches off of it for ThisWorkbook and the sheets in the workbook. Double-click on the sheet that has the "IF" statement.

Type the following code, substituting your code where appropriate:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Range("A1").Value = "Lock" Then
ActiveSheet.Protect Password:="test"
Else ActiveSheet.Unprotect Password:="test"
End If
End Sub

The "...but.":

Beware of performance issues. Effectively what this code does is check each time the selection has been changed. This code is not to overhead-intensive, but if you'regoing to do some serious calculations in the code or anything advanced you'll notice the slowdown in your worksheet performance.

All that being said, this should work for what you're looking for.

by firstpeter

Sorry - I didn't explain what the code did. Basically, the Worksheet_SelectionChange subroutine runs the code each time the selected cell changes. The IF statement checks to see if the value of cell A1 = "Lock" (case sensitive), and if so locks the worksheet with a password of "test". If it equals anything else it unlocks the worksheet using the same password.

The code is somewhat over-done, because it doesn't need to unlock it if it's not unlocked, but it does the trick.

This discussion is closed to new replies.