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