从另一个调用宏

时间:2018-04-11 10:38:19

标签: excel vba

如果用户在列D中输入值D为空的值,则运行一个弹出消息的宏。因此,一旦用户在D中输入值,用户必须在D中输入值然后在E.中输入值,通过Vlookup公式,工作表将在F列中显示一个数字。 然后第二个宏应该检查列F的值是否不等于列E中的值输入,如果不等于弹出消息。 第一部分是工作,但不是第二部分。请问任何想法。感谢

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = Cells(Target.Row, 5).Address And Target.Value <> "" And Cells(Target.Row, 4).Value = "" Then

       MsgBox "Input value in column D"
       Cells(Target.Row, 4).Select
       Target.Clear        
    End If        
Call Macro2

End Sub

Sub Macro2()

   If Target.Address = Sheets(1).Cells(Target.Row, 5).Address And Target.Value <> "" And Target.Value <> Sheets(1).Cells(Target.Row, 6).Value Then
    MsgBox "E and F don't match"

   End If

End Sub

1 个答案:

答案 0 :(得分:1)

如果第二个是问题,那么将Target传递给它:

Private Sub Worksheet_Change(ByVal Target As Range)

    Application.EnableEvents = False                    '<--- Consider removing this line
    If Target.Address = Cells(Target.Row, 5).Address _
       And Target.Value <> "" _
       And Cells(Target.Row, 4).Value = "" Then

        MsgBox "Input value in column D"
        Cells(Target.Row, 4).Select
        Target.Clear    
    End If    

    Macro2 Target        
    Application.EnableEvents = True                      '<--- Consider removing this line
End Sub

Sub Macro2(Target As Range)

    If IsError(Target) Then
        MsgBox Target.Address & "is an error!"
    ElseIf IsError(Sheets(1).Cells(Target.Row, 6)) Then
        MsgBox Sheets(1).Cells(Target.Row, 6).Address & " is an error!"
    ElseIf Target.Address = Sheets(1).Cells(Target.Row, 5).Address _
           And Target.Value <> "" _
           And Target.Value <> Sheets(1).Cells(Target.Row, 6).Value Then
        MsgBox "E and F don't match"
    End If

End Sub

但是,Target.Clear可能会在Worksheet_Change内进行循环,因为它会再次更改工作表。根据这是否正常,您可以考虑在Application.EnableEvents = False的开头或结尾处写Application.EnableEvents = TrueSub