在引用单元格时下标超出范围错误

我的代码的目标是采取一个单元格的旧值,并检查它对一个新的价值,如果它进入。 如果旧值更改为新值,则更新指定单元格中的date。

我的代码的问题是,我似乎无法find一种方法来解决这个错误,而不是我的代码中断,因此我无法修复这一行代码。 我知道我的arrays超出了界限,但是我无法弄清楚如何避开它。

这是我的代码:

Dim oldValue() Public Sub Worksheet_SelectionChange(ByVal Target As Range) oldValue = Me.Range("D4", "D21").Value End Sub Private Sub Worksheet_Change(ByVal Target As Range) If Not Intersect(Target, Me.Range("D4:D21")) Is Nothing Then Dim c As Range For Each c In Intersect(Target, Me.Range("D4:D21")) 'Here's where my code is breaking "Subscript out of range error" If oldValue(c.Row) <> c.Value Then 'Update value in column L (8 columns to the right of column D) c.Offset(0, 7).Value = Date 'or possibly "= Now()" if you need the time of day that the cell was updated End If Next End If End Sub 

在哪里突破,我已经定义,如果旧值更改为新值,然后更新date。 但它给了我一个错误,我找不到解决的办法。

如何修复我的代码,使其在范围内,任何build议?

编辑:我现在已经修复了我的代码:

 Dim oldValue As Variant Public Sub Worksheet_SelectionChange(ByVal Target As Range) 'I changed "D4", "D21" to the following: oldValue = Me.Range("D4:D21").Value End Sub Private Sub Worksheet_Change(ByVal Target As Range) If Not Intersect(Target, Me.Range("D4:D21")) Is Nothing Then 'Application.EnableEvents = False Dim c As Range For Each c In Intersect(Target, Me.Range("D4:D21")) 'Check value against what is stored in "oldValue" (row 4 is in position 1, row 5 in position 2, etc) 'I also changed the array reference If oldValue(c.Row - 3, 1) <> c.Value Then 'Update value in column L (8 columns to the right of column D) c.Offset(0, 7).Value = Date 'or possibly "= Now()" if you need the time of day that the cell was updated End If Next 'Application.EnableEvents = True End If End Sub 

 Dim oldValue as Variant .... ' oldValue is a 2D array ' and there is a shift between c.Row and the index of oldValue If oldValue(c.Row - 3, 1) <> c.Value Then ...