简体   繁体   中英

VBA excel, run macro in cell range that = to “yes”

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("z12:z15")

    If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then
        If Range("Z12:Z45).value = "yes" then
            MsgBox "Cell " & Target.Address & " has changed."
        End If
    End If
End Sub

I have problems figuring this out. any help would be appreciated. tx

luigi

In VBA, you cannot compare an array ( Range("Z12:Z45").value ) to a constant ("yes") or anything else for that matter. You need either to loop on the cells of the range (or entries of the array), or possibly use the Match or CountIf functions.

Moreover, to check for changes, you need to examine the Target range, not the Range("z12:z15") . Here's how to do it with a loop:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range, cel As Range

    ' The variable KeyCells contains the cells that will cause an alert when they are changed.
    Set KeyCells = Range("z12:z15")

    If Not Intersect(KeyCells, Target) Is Nothing Then
       For Each cel In Intersect(KeyCells, Target)
         If StrComp(cel.text, "yes", vbTextCompare) = 0 Then
           MsgBox "Cell " & cel.Address & " has changed."
         End If
       Next
    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