繁体   English   中英

Excel VBA Worksheet_Change

[英]Excel VBA Worksheet_Change

我有代码检查一系列单元格中的文本并打开一个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

这应该给你你所追求的:

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

没有真正需要一个Range变量来保持范围(“E3:E41”),你可以直接使用If Not Intersect(Range("E3:E41"), Target) Is Nothing Then

注意:由于Target是一个Range,因此不需要将它与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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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