excel 从下拉列表中选择时触发事件

l0oc07j2  于 2023-06-25  发布在  其他
关注(0)|答案(2)|浏览(345)

我需要当用户从下拉菜单中选择一个选项时,它会触发事件并锁定一定范围的单元格。我得到了锁定单元的代码,但我不能锁定它时,我选择下拉菜单。下拉菜单中字符串数据的值为ZFB50

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Address = "$K$2" Then

    With Application
     .EnableEvents = False
     .ScreenUpdating = False
     .Calculation = xlCalculationManual
    End With

If Target.Address = "ZFB50" Then

    ActiveSheet.Unprotect

    Range("E8:E100").Select
    Selection.Locked = True

    Range("C8:C100").Select
    Selection.Locked = True

    Range("D8:D100").Select
    Selection.Locked = True

    Range("F8:F100").Select
    Selection.Locked = True

    Next cell

    ActiveSheet.Protect

    With Application
     .EnableEvents = True
     .ScreenUpdating = True
     .Calculation = xlCalculationAutomatic
    End With

End If

End Sub

还是不行,这个代码有问题吗?

scyqe7ek

scyqe7ek1#

如果您使用的是数据验证下拉列表,则可以像这样使用Worksheet_Change事件:

Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$A$1" Then
    With Application
        .EnableEvents = False
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
    End With

    ' Code to lock ranges goes here

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
        .Calculation = xlCalculationAutomatic
    End With
End If
End Sub

这假设您的数据验证在单元格A1中。您必须根据您的情况更新参考资料。

elcex8rz

elcex8rz2#

这将在命名范围“my_named_range”下拉内容更改时触发事件:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim checkTarget As Range
    Set checkTarget = Application.Intersect(Target, Range("my_named_range"))
    If checkTarget Is Nothing Then
        Debug.Print "not active range, exit"
    Else
        MsgBox "success"
    End If

End Sub

相关问题