Excel中。工作表更改为工作表计算

时间:2015-08-16 19:27:25

标签: excel vba excel-vba

我的代码在" Worksheet_Change"事件

单元格中的值" A1"从实时Feed中经常更改。

我需要帮助来调整此事件的代码以使用" Worksheet_Calculate"事件

每次Cell值A1改变时,Old值必须自动显示在A2中。

A1    New Value
A2    Old Value

以下是代码:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim NewValue, OldValue
    If Target.Address <> "$A$1" Then Exit Sub
    Application.EnableEvents = False
    With Target
        NewValue = .Value
        Application.Undo
        OldValue = .Value
        .Value = NewValue
    End With
    Range("a2").Value = OldValue
        Application.EnableEvents = True
End Sub

1 个答案:

答案 0 :(得分:0)

对于一张图纸,此代码放在图纸模块中(初始旧值将为空)

Option Explicit

Private oldVal As String

Private Sub Worksheet_Calculate()
    updateOldValue Me.Range("A1")
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    updateOldValue Target
End Sub

'------------------------------------------------------------------------------------------

Public Sub updateOldValue(ByVal Target As Range)
    With Target
        If .CountLarge = 1 Then
            If .Address = "$A$1" Then
                .Offset(1, 0) = oldVal
                oldVal = .Value2
            End If
        End If
    End With
End Sub

对于多个工作表,请将此代码放在新的VBA模块中,并以相同的方式调用它:

updateOldValue Me.Range("A1")updateOldValue Target

Option Explicit

Private oldVal As String

Public Sub updateOldValue(ByVal Target As Range)
    With Target
        If .CountLarge = 1 Then
            If .Address = "$A$1" Then
                .Offset(1, 0) = oldVal
                oldVal = .Value2
            End If
        End If
    End With
End Sub