Tuesday, September 26, 2006

Excel and VBA - Locking a Cell

Its been a long time I even saw any code in VB let alone VBA. That was until somebody asked me how they could lock a particular cell in excel based on the list selection in another cell.

That as usual sent me googling and finally I managed to write a script that will do the job for me. For writing the code, I opened the excel sheet and pressed Alt + F11 to open the Macro VBA Editor and selected the worksheet for which I wanted to write the functionality for and then wrote this piece of code on the worksheet change event. I wanted to lock cells C1 to C10 based on the value of cell D1.

Private Sub Worksheet_Change(ByVal Target As Range)
If (Intersect(Target, Range("D1")) Is Nothing) Or _
                    (Target.Cells.Count > 1) Or _
                    Not (Target.Column = 4 And Target.Row = 1) Then Exit Sub
         If Range("D1").Value = "V1" Then
                  ActiveSheet.Unprotect
                  Range("A1:IV65536").Locked = False
                  Range("C1:C10").Locked = True
                  ActiveSheet.Protect
         Else
                  ActiveSheet.Unprotect
                  Range("A1:IV65536").Locked = False
         End If
End Sub

Then my colleague wanted something different. He said, that he wanted the user to be alerted that value cannot be entered into a cell based on the selected value of another cell for which I modified the above code slightly to get this:

Private Sub Worksheet_Change(ByVal Target As Range)
If Not (Target.Column = 6 Or _
           Target.Column = 9 Or _
            Target.Column = 12) Then Exit Sub
    If Not (ActiveSheet.Cells(Target.Row, Target.Column - 1).Value = "C")  _
     And Not (ActiveSheet.Cells(Target.Row, Target.Column).Value = "")       
     Then
             MsgBox ("No value possible here")
             ActiveSheet.Cells(Target.Row, Target.Column).Value = ""
    End If
End Sub

The above code alerts the user if the user tries to enter some value in a cell when it makes no sense to do so because of the selected value of another column.

No comments: