Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
953 views
in Technique[技术] by (71.8m points)

excel - Trigger event when select from dropdown

I need when a user selects an option from the dropdown menu, it will trigger the event and lock down certain range of cells. I got the codes for lockdown cell but I can't lock it down when I select the dropdown menu. The value of the string data in the dropdown menu is 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

It still doesn't work, is there any problem with this code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you're using a data validation dropdown, you can use the Worksheet_Change event like so:

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

This assumes that your data validation is in cell A1. You'll have to update the reference as appropriate for your situation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...