4

我需要当用户从下拉菜单中选择一个选项时,它会触发事件并锁定特定范围的单元格。我获得了锁定单元的代码,但是当我选择下拉菜单时无法将其锁定。下拉菜单中字符串数据的值为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

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

4

2 回答 2

4

如果您使用的是数据验证下拉菜单,则可以像这样使用 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 中。您必须根据您的情况更新参考。

于 2013-06-27T16:43:28.827 回答
1

可以在这里找到一个带有命名范围的示例:

http://www.sebastianviereck.de/en/VBA-dropdown-change-event-to-perform-action/

于 2017-06-06T09:08:54.507 回答