简体   繁体   中英

Excel VBA Worksheet_Change

I have code that checks for text in a range of cells and opens a MsgBox

The code works well until I delete a range of data both from using a macro for ClearContents and selecting a range of cells and using the delete button. No error if I delete cell contents one cell at a time .

The original code would trigger the MsgBox for every change; I just want it to trigger based on the entry of "Not Met" from a pick list.

The error I get is this:

Run-time error '13': Type mismatch

Following is the modified code:

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

This should give you what you are after:

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

There is no real need to have a Range variable to keep the the Range("E3:E41"), you can do it directly with If Not Intersect(Range("E3:E41"), Target) Is Nothing Then .

Note: Since Target is a Range, there is no need to use it with Range(Target.Address) , Target alone will do it.

Code (short version)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM