Excel VBA Worksheet_Change
我有代码检查单元格范围内的文本,并打开一个MsgBox
代码运行良好,直到我删除了一个范围的数据都使用一个macros的ClearContents
和select一个区域的单元格,并使用删除button。 如果我一次删除一个单元格的单元格内容,则无错误 。
原始代码将触发MsgBox
的每一个变化; 我只是希望它根据从select列表中input“Not Met”来触发。
我得到的错误是这样的:
运行时错误“13”:types不匹配
以下是修改后的代码:
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
有没有真正的需要有一个范围variables保持范围(“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
这应该给你后面的东西:
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