VBA - 如果单元格包含一个单词,则消息框仅一次

问题描述

我的想法是每次我在 A 列的单元格中输入“高”这个词时都会收到警报(如果该词包含在更长的字符串中)。如果我编辑一个单元格并且我的文本包含“高”并且我确认(当我在单元格上按“输入”以确认或只离开编辑的单元格时显示警报),此警报应该弹出。所以我做了这个代码

Private Sub Worksheet_Change(ByVal Target As Range)
If Not IsError(Application.Match("*high*",Range("A:A"),0)) Then
       MsgBox ("Please check 2020 assessment")
End If
End Sub

代码似乎工作正常。我在 A 列的单元格中数字“高”,并在我确认离开单元格时收到警报。 问题是,当我有一个“高”单元格时,警报会在我每次修改时继续弹出,在每个单元格中。所以是不可能在工作表上工作的。 我需要一个代码来确保,在数字“高”之后,我只收到一次警报,然后在编辑任何单元格时我不会收到其他人,除非我在另一个单元格中数字“高”,或者我去修改一个已经包含“高”的单元格,我再次确认。 我能做什么?谢谢!!

解决方法

这将设置一个目标(监视范围)并检查更改的第一个单元格是否包含该单词

请注意,如果您不想在修改范围时检查更改的每个单元格(例如,当您复制和粘贴多个单元格时),则必须使用循环

Private Sub Worksheet_Change(ByVal Target As Range)
    
    ' Set the range that will be monitored when changed
    Dim targetRange As Range
    Set targetRange = Me.Range("A:A")
    
    ' If cell changed it's not in the monitored range then exit sub
    If Intersect(Target,targetRange) Is Nothing Then Exit Sub
    
    ' Check is cell contains text
    If Not IsError(Application.Match("*high*",targetRange,0)) Then
        ' Alert
        MsgBox ("Please check 2020 assessment")
    End If
    
End Sub

让我知道它是否有效

,

我试过你的代码;现在,如果“A”列有一个“高”单元格,警报会正确弹出,然后如果我编辑“A”列以外的列中的单元格,我不会收到警报,所以这是个好消息!

坏消息是,如果我在 A 列中有一个“高”,当我在“A”列本身中编辑任何其他单元格时,我仍然每次都会收到警报。

,

工作表更改:目标包含字符串

  • 无论您输入一个还是多个条件值,消息框只会显示一次。

代码

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    
    Const srcCol As String = "A"
    Const Criteria As String = "*high*"
    
    Dim rng As Range: Set rng = Intersect(Columns(srcCol),Target)
    If rng Is Nothing Then
        Exit Sub
    End If
    
    Application.EnableEvents = False
    
    Dim aRng As Range
    Dim cel As Range
    Dim foundCriteria As Boolean
    For Each aRng In rng.Areas
        For Each cel In aRng.Cells
            If LCase(cel.Value) Like LCase(Criteria) Then
                MsgBox ("Please check 2020 assessment")
                foundCriteria = True
                Exit For
            End If
        Next cel
        If foundCriteria Then
            Exit For
        End If
    Next aRng
    
    Application.EnableEvents = True
    
End Sub

Sub testNonContiguous()
    Range("A2,A12").Value = "high"
End Sub