在一个工作表中运行多个“Private Sub Worksheet_Change(ByVal Target As Range)”

时间:2014-02-09 11:00:52

标签: excel excel-vba vba

我试图将2个代码合并到一个Private Sub中,而第一个运行正常,第二个代码根本没有被提取。它不会返回任何错误,它不会调用所需的Sub。任何帮助将不胜感激。

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo justenditall
    Application.EnableEvents = False


    If Not Intersect(Target, Range("e6:e1000, M6:m1000")) Is Nothing Then
        If Target.Value <> "" Then
        ActiveSheet.Unprotect Password:="password"
        Target.Locked = True
        ActiveSheet.Protect Password:="password"
        End If

    Next

    ElseIf Not Intersect(Target, Range("P1")) Is Nothing Then
        If Target.Value = 1 Then
        Call SetRecipients
        End If
    Next

justenditall:
    Application.EnableEvents = True
End Sub

1 个答案:

答案 0 :(得分:1)

您的代码有Next,这不是必需的。你错过了End If。我很惊讶代码正在运行以执行第一个IF / ENDIF

这对我有用(尝试和测试

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo justenditall
    Application.EnableEvents = False

    If Not Intersect(Target, Range("e6:e1000, M6:m1000")) Is Nothing Then
        If Target.Value <> "" Then
            ActiveSheet.Unprotect Password:="password"
            Target.Locked = True
            ActiveSheet.Protect Password:="password"
        End If
    ElseIf Not Intersect(Target, Range("P1")) Is Nothing Then
        If Target.Value = 1 Then
        Call SetRecipients
        End If
    End If
LetsContinue:
    Application.EnableEvents = True
    Exit Sub
justenditall:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

Sub SetRecipients()
    MsgBox "Second One Runs"
End Sub