1
我的代码的目标是获取单元格的旧值,并在输入新值时对其进行检查。如果旧值更改为新值,则更新指定单元格中的日期。当引用单元格时下标超出范围错误
我的代码的问题是,我似乎无法找到一种方法来解决这个错误,而不会破坏我的代码,因此我无法修复这一行代码。我知道我的阵列超出界限或者沿着这些界限,但我无法弄清楚如何避开它。
这里是我的代码:
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
如果它打破,我已经定义,如果旧值更改为新的值,然后更新日期。但它给我一个错误,我找不到解决的办法。
我该如何解决我的代码,使其在范围内,任何建议?
编辑:我现在已经修好了我的代码:
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
它仍然给我的错误。 – juiceb0xk
@ juiceb0xk我看到,由于索引转移,仍然存在错误。 oldValue从1到18,而c.Row从4到21.我将这个更正加到答案上。 –
哦,我现在看到我的问题了!我已经修复了我的代码。谢谢你的帮助。 – juiceb0xk