只有在input特定input值后才运行VBA代码

我试图做一个macros,当有人在D20:D50的范围内键入“New Hire”时,它会调用一个macros。 我知道我可以做一个If但问题是,有很多细胞和大量的代码。 我需要使用ByVal Target As Range ,因为每当他们键入我想调用一个macros的单词。

 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范围内input“New Hire”来进行活动?

您可以在工作表模块中使用给定的代码。 这里的主线是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,在您的项目窗口中select您需要的工作表并粘贴代码。