仅在输入特定输入值后运行VBA代码

时间:2015-06-24 14:30:20

标签: excel vba excel-vba events

我正在尝试做一个宏,每当有人在D20:D50范围内输入“新雇用”时,它就会调用一个宏。我知道我可以用If来做,但问题是有很多单元格和很多代码。我需要使用ByVal Target As Range,因为每当他们输入我想要调用宏的单词时。

If Target.Address = "$D$20" Then

        If Range("D20").Value = "New Hire" Then

            MsgBox "Please Fulfill the New Hire(s) Information in the following New Hire Sheet" & vbNewLine & "Important Note" & vbNewLine & "Include the New Employee's ID and Bank documentation with Account Number information"
            Call NewHireForm    

ElseIf Target.Address = "$D$21" Then

        If Range("D21").Value = "New Hire" Then

            MsgBox "Please Fulfill the New Hire(s) Information in the following New Hire Sheet" & vbNewLine & "Important Note" & vbNewLine & "Include the New Employee's ID and Bank documentation with Account Number information"
            Call NewHireForm

你看,它没有简化。有没有办法在D20D50范围内输入“新员工”来制作活动?

1 个答案:

答案 0 :(得分:1)

您可以在工作表模块中使用给定的代码。这里的主线是If Not Intersect(Target, Me.Range("D20:D50")) Is Nothing Then。它表示只有在Range("D20:D50")内的值发生变化时才会执行代码。

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error GoTo errH
    Dim cell As Range
    If Not Intersect(Target, Me.Range("D20:D50")) Is Nothing Then
        Application.EnableEvents = False
        For Each cell In Target
            If cell.Value = "New Hire" Then
                MsgBox "Please Fulfill the New Hire(s) Information in the following New Hire Sheet" & vbNewLine & "Important Note" & vbNewLine & "Include the New Employee's ID and Bank documentation with Account Number information"
                Call NewHireForm
            End If
        Next
    End If
errH:
    If Err.Number <> 0 Then MsgBox Err.Number & " " & Err.Description
    Application.EnableEvents = True
End Sub

您需要打开VBE,在项目窗口中选择您需要的工作表并粘贴代码。