【问题标题】:Program returns message box again and again if 'no' is pressed in message box?如果在消息框中按下“否”,程序会一次又一次地返回消息框?
【发布时间】:2016-02-06 15:43:34
【问题描述】:

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

1.如果在消息框中按“否”,它会一次又一次地返回消息框?

2。如果在空白单元格上按 Enter,我不希望出现消息框?

这里是代码

 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

【问题讨论】:

    标签: vba excel vlookup


    【解决方案1】:

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

    2:在代码开头检查target是否为空。

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

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

    我也简化了一些,去掉了一些无用的结构。

     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
    

    【讨论】:

      猜你喜欢
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 2018-08-08
      • 1970-01-01
      • 2016-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多