Macro that looks at the output of the cell rather than the formula
我使用了Microsoft网页上的代码,因此,每次更改范围内的单元格时,都会出现一个消息框,自动告诉我发生了这种情况。该页面是:
https://support.microsoft.com/zh-CN/kb/213612
我复制并粘贴的代码是(我对其进行了非常小的编辑-编辑在下面的代码中):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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("B1:B10") 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. MsgBox"Cell" & Target.Address &" has changed." End If End Sub |
但是这段代码并没有完全按照我的意愿去做。在B10内,我有一个公式:
1 | =IF(D10="709A", IF(AND(D10="709A"),"Yes","No"),"") |
公式本身并不重要,而是公式的作用。如果用" 709A"输入D10,则公式在B10中输出"是"。因此,据我所知,如果我在D10中输入" 709A",则应该从宏中自动获得一个消息框,因为它会更改B10的值。但是我没有。即使公式本身发生更改,我也只会收到一个消息框,即使输出(值/单元格中的可见内容-是否为此有技术标签?)没有更改也是如此。如何创建一个宏,该宏可以在单元格的输出发生变化时自动告诉我?即:这告诉我,当用" 709A"输入D10时,输出已从"变为"是?
与Roman B \\的建议类似的解决方法,但使用全局数组。激活工作表时,这会将值存储在B1:B10中,然后每次在工作表中进行更改时都会检查并更新。这可能不是理想的解决方案,但似乎仅检查10个单元格就可以完成工作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | Option Explicit Option Base 1 Dim globalArray(10) Sub Worksheet_Activate() Dim i As Long For i = 1 To 10 globalArray(i) = Cells(i, 2) Next i End Sub Private Sub Worksheet_Change(ByVal Target As Range) Dim i As Long For i = 1 To 10 If globalArray(i) <> Cells(i, 2) Then ' Do stuff here ' globalArray(i) = Cells(i, 2) End If Next i End Sub |
我可以想到的解决方法是在Worksheet_Change事件中具有一个变量数组,该变量数组将存储每个关键单元格的.value或.value2属性,并将其与更改后的单元格进行比较,并触发您的消息那样的盒子。问题在于,代码太笨拙了,您开始观看的关键单元越多,代码就会变得越笨。
可以访问单元格的
MSDN页面包含有关这些范围成员的更多信息。此页面解决了属性之间的差异。