合并2个工作表_更改事件

时间:2018-11-07 08:22:16

标签: excel vba excel-vba

我有两个Worksheet_Change事件子项,它们各自可以完美地工作,但是我需要组合这些子项来测试两个范围“ G2”或“ G3”中任何一个的条件。我已经尝试了搜索中的所有选项,但不能让它起作用,我将不胜感激。 以下是两个Sub:

Private Sub Worksheet_Change(ByVal Target As Range)

    If Intersect(Target, Range("G2")) Is Nothing Then Exit Sub
    If Target.Count > 1 Then Exit Sub

          Dim lr As Long
          lr = Range("B" & Rows.Count).End(xlUp).Row

    Application.ScreenUpdating = False

          Range("Z7:Z" & lr) = "=ISERROR(MATCH(G$2,B7:O7,0))"
          Range("Z7", Range("Z" & Rows.Count).End(xlUp)).AutoFilter 1, False

    Application.ScreenUpdating = True
    Call activate_button_31


End Sub

Private Sub Worksheet_Change(ByVal Target As Range)

    If Intersect(Target, Range("G3")) Is Nothing Then Exit Sub
    If Target.Count > 1 Then Exit Sub

          Dim lr As Long
          lr = Range("B" & Rows.Count).End(xlUp).Row

    Application.ScreenUpdating = False

          Range("Q7:Q" & lr) = "=ISERROR(MATCH(G$3,B7:O7,0))"
          Range("Q7", Range("Q" & Rows.Count).End(xlUp)).AutoFilter 1, False

    Application.ScreenUpdating = True
    Call activate_button_40


End Sub

请告知我是否需要其他信息。

亲切问候

Coenie

2 个答案:

答案 0 :(得分:0)

尝试一下:

Private Sub Worksheet_Change(ByVal Target As Range)

    If Target.Count > 1 Then Exit Sub
    Dim lr As Long
    lr = Range("B" & Rows.Count).End(xlUp).row

    Application.ScreenUpdating = False

    If Not Intersect(Target, Range("G2")) Is Nothing Then
        Range("Z7:Z" & lr) = "=ISERROR(MATCH(G$2,B7:O7,0))"
        Range("Z7", Range("Z" & Rows.Count).End(xlUp)).AutoFilter 1, False
        Call activate_button_31

    ElseIf Not Intersect(Target, Range("G3")) Is Nothing Then
        Range("Q7:Q" & lr) = "=ISERROR(MATCH(G$3,B7:O7,0))"
        Range("Q7", Range("Q" & Rows.Count).End(xlUp)).AutoFilter 1, False
        Call activate_button_40
    End If

    Application.ScreenUpdating = True
End Sub

答案 1 :(得分:0)

一种组合例程的方法:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim lr As Long

    On Error GoTo Terminate
    If Target.Count > 1 Then GoTo Terminate
    xlQuiet True
    lr = Range("B" & Rows.Count).End(xlUp).Row

    If Not Intersect(Target, Range("G2")) Is Nothing Then
        With Range("Z7:Z" & lr)
            .Formula = "=ISERROR(MATCH(G$2,B7:O7,0))"
            .AutoFilter 1, False
        End With
        xlQuiet False
        Call activate_button_31
    ElseIf Not Intersect(Target, Range("G3")) Is Nothing Then
        With Range("Q7:Q" & lr)
            .Formula = "=ISERROR(MATCH(G$3,B7:O7,0))"
            .AutoFilter 1, False
        End With
        xlQuiet False
        Call activate_button_40
    End If

Terminate:
    If err Then
        Debug.Print "Error", err.Number, err.Description
        err.clear
    End If
    xlQuiet False

End Sub

Private Sub xlQuiet(Optional ByVal b As Boolean)
    With Application
        .ScreenUpdating = Not b
        .EnableEvents = Not b
    End With
End Sub