VBA excel,在单元格范围内运行macros=“是”

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

路易吉

在VBA中,你不能将一个数组( Range("Z12:Z45").value )与一个常量(“yes”)或其他任何东西进行比较。 您需要循环范围的单元格(或数组的条目),或者可能使用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