2015-08-16 105 views
-1

我有「Worksheet_Change」事件完美運行的代碼。Excel。工作表更改爲工作表計算

單元格「A1」中的值經常會從實時Feed中更改。

我需要幫助,才能使此事件的代碼適應「Worksheet_Calculate」事件。

每當單元格值A1發生變化時,自動舊值必須顯示在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 

回答

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