如何使用时间戳记VBA / Excel将动态值历史记录保留到行

时间:2018-09-28 09:40:27

标签: excel vba excel-vba

我是VBA的新手,我正想制作一个脚本以使其正常工作。 目标: 我在A10单元上有一个动态数字,每隔几天或几小时,它的值就会根据公式进行更改。 我想保留此单元格曾经拥有的所有价值... 我找不到用公式执行此操作的任何方法,因此我尝试使用VBA,并编写了以下脚本:

    Dim xVal As String
Private Sub Worksheet_Change(ByVal Target As Range)
    Static xCount As Integer
    Application.EnableEvents = False
    If Target.Address = Range("A10").Address Then
        Range("D2").Offset(xCount, 0).Value = xVal
        Range("C2").Offset(xCount, 0).Value = Now()
        xCount = xCount + 1
    Else
        If xVal <> Range("A10").Value Then
         Range("D2").Offset(xCount, 0).Value = xVal
         Range("C2").Offset(xCount, 0).Value = Now()
        xCount = xCount + 1
        End If
    End If
    Application.EnableEvents = True
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    xVal = Range("A10").Value
End Sub

我的特定脚本有两个问题:

  • 尽管每次打开工作簿时我都将其保存为.xlsm,但脚本会覆盖C2开头的值,因此我会丢失以前的值...
  • 我不知道为什么,但是尽管脚本运行顺利,但仍保留了单元格A10的先前值,而不是当前值。

能给我您的帮助吗?

谢谢

1 个答案:

答案 0 :(得分:2)

仅尝试以下代码:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim xCount As Long

    Application.EnableEvents = False

    xCount = Cells(ActiveSheet.Rows.Count, 3).End(xlUp).Row - 1

    If Target.Address = Range("A10").Address Then
        Range("D2").Offset(xCount, 0).Value = Range("A10").Value
        Range("C2").Offset(xCount, 0).Value = Now()
    Else
        If xVal <> Range("A10").Value Then
         Range("D2").Offset(xCount, 0).Value = Range("A10").Value
         Range("C2").Offset(xCount, 0).Value = Now()
        End If
    End If

    Application.EnableEvents = True

End Sub

当我在“ A10”中放置函数= NOW()时,有时复制到“ D”中的“ A10”中的= NOW()显示的时间比“ C”中的时间值早第二个时间,但我想这是没问题。

编辑:

Option Explicit ' To be sure there are not misspelled variables

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim xCount As Long
    Dim valueCell As Range
    Dim timeStampCell As Range
    Dim targetCell As Range
    Dim xVal As Long

    Application.EnableEvents = False

    '''''EDIT''''''

    Set targetCell = Range("A10")
    Set timeStampCell = Range("C2")
    Set valueCell = timeStampCell.Offset(0, 1)

    '''''''''''''''

    xCount = Cells(ActiveSheet.Rows.Count, valueCell.Column).End(xlUp).Row - 1 ' Now it is not checking the third column but the valueCell column

    If Target.Address = targetCell.Address Then
        valueCell.Offset(xCount, 0).value = targetCell.value
        timeStampCell.Offset(xCount, 0).value = Now()
    Else
        If valueCell.Offset(Cells(ActiveSheet.Rows.Count, valueCell.Column).End(xlUp).Row - 2, 0).value <> targetCell.value Then  ' Now duplicates, I forgot I got rid of xVal variable
         valueCell.Offset(xCount, 0).value = targetCell.value
         timeStampCell.Offset(xCount, 0).value = Now()
        End If
    End If

    Application.EnableEvents = True

End Sub