使用VBA如何检测工作表中的任何值何时更改?

时间:2015-05-28 17:47:06

标签: excel excel-vba vba

我有一个工作表,其中包含几个包含数百个值的列。我希望单元格A1说" Value Changed"只要工作表中的任何值发生更改。我尝试制作一些代码,如下所示,但我无法想到如何捕获OriginalValue变量中的原始值。如何检测任何单元格中的值何时从不同于目标值的内容发生变化?

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Value <> OriginalValue Then
    Range("A1").Value = "Value Change"
End If

End Sub

2 个答案:

答案 0 :(得分:2)

继续我的评论看到这一点。我已对代码进行了评论,因此您无需理解它。但如果你这样做,那就干脆问。 :)

Dim PrevValue As Variant

Private Sub Worksheet_Change(ByVal Target As Range)

    '~~> Check if more than 1 cell is changed
    If Target.Cells.CountLarge > 1 Then Exit Sub

    '~~> Check if the change didn't happen in A1
    If Not Intersect(Target, Range("A1")) Is Nothing Then Exit Sub

    On Error GoTo Whoa

    Application.EnableEvents = False

    '~~> Compare
    If Target.Value <> PrevValue Then
        Range("A1").Value = "Value of " & Target.Address & " changed from " & _
                            PrevValue & " to " & Target.Value

        '~~> Store new value to previous value
        PrevValue = Target.Value
    End If

Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    PrevValue = Target.Value
End Sub

答案 1 :(得分:0)

您可以“暂时取消”以检索原始值:

<div id="divNetworkGrid">
                <div id="{{network.id}}" ng-repeat="network in networks">
                    <span>
                        <table>
                            <tr>
                                <td class="imgContainer">
                                    <img ng-src="{{'assets/img/networkicons/'+(network.actual || 'default' )+'.png'}}"/>
                                </td>
                            </tr>
                        </table>
                    </span>
                </div>
            </div>

这仅适用于单细胞。