如果' no',程序会一次又一次地返回消息框。在消息框中按下了吗?

时间:2016-02-06 15:43:34

标签: vba excel-vba vlookup excel

程序的功能是将vlookup的结果返回到要查找的值的同一单元格中,但它有两个问题。

1。如果' no'它会一次又一次地返回消息框。在消息框中按下了吗?

2。如果在空白单元格上按下输入,我不想显示消息框吗?

这是代码

 Sub Worksheet_Change(ByVal Target As Range)

  Dim Ret_type As Integer
  Dim strMsg As String
  Dim strTitle As String
  If Target.Count > 1 Then Exit Sub
  If Not Intersect(Target, Range("A1:A114")) Is Nothing Then
     Application.EnableEvents = False
     Table2 = Sheet2.Range("C2:D3")
     strTitle = "Alert"
     strMsg = "Combination not found press Yes for manual entry"

     On Error Resume Next
        Target.Value = Application.WorksheetFunction.VLookup(Target.Value, Table2, 2, False)
         Application.EnableEvents = True
         If Err.Number <> 0 Then
           Ret_type = MsgBox(strMsg, vbYesNo, strTitle)
              Select Case Ret_type
               Case 7
                ActiveCell.Offset(-1, 0).Clear
              End Select
         End If
         On Error GoTo 0 ''no error, coming back to default conditions 
  End If
End Sub

1 个答案:

答案 0 :(得分:0)

1:确保仅在代码进行每次更改后重新启用事件。否则它将继续在递归中重新启动。

2:如果目标为空,请检查代码的开头。

+1:不要在像这样的宏中使用activecell.offset;您的用户可能已经单击了任何单元格,在这种情况下,偏移是没有意义的。改为使用Target变量。

你的代码非常混乱,我不确定它在这一点上是否完全合理。无论如何,这是一个工作版本。有关兴趣点,请参阅我的在线评论。

我也简化了一点,删除了一些无用的结构。

 Sub Worksheet_Change(ByVal Target As Range)

  Dim strMsg As String
  Dim strTitle As String

  If Target.Cells.Count > 1 Then Exit Sub
  If Target.Value = "" Then Exit Sub 'don't bother with a blank cell

  If Not Intersect(Target, Range("A1:A114")) Is Nothing Then
    Application.EnableEvents = False
    Table2 = Sheet2.Range("C2:D3")
    strTitle = "Alert"
    strMsg = "Combination not found press Yes for manual entry"

    On Error Resume Next
      Target.Value = Application.WorksheetFunction.VLookup(Target.Value, Table2, 2, False)
      If Err.Number <> 0 Then
        If MsgBox(strMsg, vbYesNo, strTitle) = vbYes Then
          Target.Clear 'Better than the offset version; this works also if your user uses tab or mouse click, not only enter
        End If
      End If
    On Error GoTo 0
    Application.EnableEvents = True 'only re-enable events AFTER having changed everything you want to change
  End If
End Sub