the goal of my code is to take the old value of a cell, and check it against a new value, if it is entered. And if the old value changes to a new value, then update the date in a cell specified.
我的代码的目标是获取单元格的旧值,并在输入新值时将其与新值进行检查。如果旧值更改为新值,则在指定的单元格中更新日期。
The problem with my code is that I cannot seem to find a way to get around this error without my code breaking, thus I am having trouble trying to fix this one line of code. I know my array is out of bounds or something along those lines, but I cannot figure out how to get around it.
我的代码的问题是,我似乎无法找到一种方法在不破坏代码的情况下绕过这个错误,因此我在试图修复这一行代码时遇到了麻烦。我知道我的数组是不允许的或者类似的东西,但是我不知道怎么绕过它。
Here's my code:
这是我的代码:
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
Where it's breaking, I have defined that if the old value changes to the new value, then update the date. But it's giving me an error that I cannot find a way to fix.
在发生故障的地方,我定义了如果旧值更改为新值,则更新日期。但它给了我一个错误,我找不到修正的方法。
How can I fix my code to get it within range, any suggestions?
如何修改代码使其在范围内,有什么建议吗?
EDIT: I've now fixed my code:
编辑:我已经修正了我的代码:
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
1 个解决方案
#1
1
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 ...
#1
1
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 ...