2017-01-20 115 views
1

我有一个单元格区域检查文本并打开一个MsgBoxExcel的VBA Worksheet_Change

代码工作很好,直到我无论从使用宏ClearContents,选择单元格区域删除某个范围内的数据的代码并使用删除按钮。 如果我一次删除一个单元格的单元格内容,没有错误

原始代码会触发MsgBox进行每次更改;我只是希望它根据选择列表中的“未达到”条目触发。

我得到的错误是这样的:

运行时错误 '13':类型不匹配

下面是修改后的代码:

Private Sub Worksheet_Change(ByVal Target As Range) 

Dim KeyCells As Range 
    ' The variable KeyCells contains the cells that will 
    ' cause an alert when they are changed. 
    Set KeyCells = Range("E3:E41") 

    If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then 


     ' Display a message when one of the designated cells has been 
     ' changed. 
     ' Place your code here. 

     If Target.Value = ("Not Met") Then 
     MsgBox "Make sure you enter Gaps, Actions and a Priority Rating" 

    End If 
    End If 

End Sub 
+1

那是因为你不是在这个时候选择运行更多的细胞。如果只有一个单元格发生更改,您需要输入一个支票才能运行 –

回答

0

没有必要让范围变量保持范围(“E3:E41”),您可以直接使用If Not Intersect(Range("E3:E41"), Target) Is Nothing Then

注:由于Target是一个范围,也没有必要使用它与Range(Target.Address),单独Target会做到这一点。

代码(精简版)

Private Sub Worksheet_Change(ByVal Target As range) 

    If Not Intersect(Range("E3:E41"), Target) Is Nothing Then 
     ' Display a message when one of the designated cells has been changed 
     If Target.Value = ("Not Met") Then MsgBox "Make sure you enter Gaps, Actions and a Priority Rating" 
    End If 

End Sub 
+0

感谢Shai Rado提供的额外信息。 –

0

这应该给你你在做什么之后:

Private Sub Worksheet_Change(ByVal Target As Range) 

Dim KeyCells As Range 
    ' The variable KeyCells contains the cells that will 
    ' cause an alert when they are changed. 
    Set KeyCells = Range("E3:E41") 

    If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then 


     ' Display a message when one of the designated cells has been 
     ' changed. 
     ' Place your code here. 

     If Target.Count = 1 Then 
      If Target.Value = ("Not Met") Then 
       MsgBox "Make sure you enter Gaps, Actions and a Priority Rating" 
      End If 
     End If 
    End If 

End Sub 
+0

这是一个很好的解决方法Craig T –