Excel VBA自动将行创builddate和更新date(连续的任何单元格)存储到不同的单元格中

我试图在Excel工作表创build一个VBA代码,我可以自动插入创builddate(一旦数据被插入一行)和更新date(一旦该行的任何单元格值从以前的值更改)。 我试了下面的代码,我可以得到创builddate,但不是更新date。

我得到这个错误

types不匹配

在线上:

If Cells(Target.Row, i).Value <> PrevVal(Target.Row, i) Then 

我想问题是,我不知道如何正确捕获单元格的前一个值,以便将其与新值进行比较。

供参考:我的桌子是这样的:

 Id Position1 Position2 DATE Created Date updated Data1 Data2 .... 

 Dim PrevVal As Variant Private Sub Worksheet_SelectionChange(ByVal Target As Range) On Error GoTo ExitGraceFully If Selection.Rows.Count = 1 And Selection.Columns.Count = 1 Then PrevVal = Selection.Value Else PrevVal = Selection End If ExitGraceFully: End Sub Private Sub Worksheet_Change(ByVal Target As Range) If Not Intersect(Range("B:B"), Target) Is Nothing Or Not Intersect(Range("C:C"), Target) Is Nothing Then Cells(Target.Row, 1).Value = Cells(Target.Row, 2) & Cells(Target.Row, 3) If Cells(Target.Row, 4).Value = "" Then Cells(Target.Row, 4).Value = Date & " " & Time Cells(Target.Row, 4).NumberFormat = "m/d/yyyy h:mm AM/PM" End If End If Dim i As Integer If Target.Rows.Count = 1 And Target.Columns.Count = 1 Then For i = 2 To 50 If Cells(Target.Row, i).Value <> PrevVal(Target.Row, i) Then Cells(Target.Row, 5).Value = Date & " " & Time Cells(Target.Row, 5).NumberFormat = "m/d/yyyy h:mm AM/PM" End If Next i End If End Sub 

我终于纠正了我的代码,现在运行良好。

 Dim PrevVal As Variant Private Sub Worksheet_SelectionChange(ByVal Target As Range) On Error GoTo ExitGraceFully If Selection.Rows.Count = 1 And Selection.Columns.Count = 1 Then PrevVal = Target.Value Else PrevVal = Target End If ExitGraceFully: End Sub Private Sub Worksheet_Change(ByVal Target As Range) If Not Intersect(Range("B:C"), Target) Is Nothing Then Cells(Target.Row, 1).Value = Cells(Target.Row, 2) & Cells(Target.Row, 3) If Cells(Target.Row, 4).Value = "" Then Cells(Target.Row, 4).Value = Date & " " & Time Cells(Target.Row, 4).NumberFormat = "m/d/yyyy h:mm AM/PM" End If End If If Not Intersect(Range("F:Z"), Target) Is Nothing Then Application.EnableEvents = False If (PrevVal <> "") And (Cells(Target.Row, Target.Column).Value <> PrevVal) Then Cells(Target.Row, 5).Value = Date & " " & Time Cells(Target.Row, 5).NumberFormat = "m/d/yyyy h:mm AM/PM" End If End If Application.EnableEvents = True End Sub