如何根据条件

时间:2015-12-14 12:29:13

标签: excel vba excel-vba

我想根据前一个单元格的条件禁用excel中的一个单元格,例如,如果A3 =“xyz”,那么B3 =禁用,我通过以下代码实现了这一点:

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

现在我想将此代码用于整个A列。如果我输入A4A5,则应禁用相应的B4B5

1 个答案:

答案 0 :(得分:3)

这应该可以正常工作:

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