VBA优秀,在单元格范围内运行宏,即="是"

时间:2017-07-30 01:41:33

标签: excel vba excel-vba

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

我有问题解决这个问题。任何帮助,将不胜感激。 TX

路易

1 个答案:

答案 0 :(得分:4)

在VBA中,您无法将数组(Range("Z12:Z45").value)与常量("是")或其他任何内容进行比较。您需要循环范围的单元格(或数组的条目),或者可能使用MatchCountIf函数。

此外,要检查更改,您需要检查Target范围,而不是Range("z12:z15")。以下是如何使用循环执行此操作:

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