Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use the vb code for the entire column based on the condition

Tags:

excel

vba

I want to disable one cell in excel based on the condition of the previous cell, for example, if A3="xyz" then B3= disable, and I have achieved this by the following code:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target <> Range("A3") Then Exit Sub

    ActiveSheet.Unprotect

    If Range("A3").Value = "CNS" Then
        Range("B3").Locked = True
    End If

    If Range("A3").Value = "APL" Then
        Range("B3").Locked = False
    End If

    ActiveSheet.Protect

End Sub

Now I want to use this code for the entire A column. If I enter A4 or A5, then the corresponding B4 or B5 should become disabled.

like image 634
nina Avatar asked Jan 25 '26 01:01

nina


1 Answers

This should work just fine :

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Cells.Count > 1 Then Exit Sub
    Application.EnableEvents = False

    If Not Application.Intersect(Target, Me.Columns(1)) Is Nothing Then
        ActiveSheet.Unprotect
        Select Case UCase(Target.Value)
            Case Is = "CNS"
                Target.Offset(0, 1).Locked = True
            Case Is = "APL"
                Target.Offset(0, 1).Locked = False
            Case Else
                MsgBox "Value not covered by the program", vbInformation + vbOKOnly
        End Select
        ActiveSheet.Protect
    Else
    End If
    Application.EnableEvents = True
End Sub
like image 184
R3uK Avatar answered Jan 27 '26 15:01

R3uK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!