Excel VBA Worksheet_Change

时间:2017-01-20 02:57:25

标签: excel vba excel-vba

我有代码检查一系列单元格中的文本并打开一个MsgBox

代码运行良好,直到我使用ClearContents的宏并选择一系列单元格并使用删除按钮删除一系列数据。 如果我一次删除一个单元格的单元格内容,则没有错误

原始代码会在每次更改时触发MsgBox;我只是希望它基于" Not Met"的输入而触发。从选择列表中。

我得到的错误是:

  

运行时错误' 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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

没有必要使用Range变量来保持范围(" 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