VBA从单元格更改之前保存值
我有一个电子表格,我实现了一个计分板。 我需要的行为是当有分数值的单元格在靠近它的单元格上升时,在列b上,将它的颜色更改为绿色,当单元格分数值下降到靠近它的单元格时,它将颜色更改为红色。
分数变化的单元格范围是e5:e67
简而言之:当用户在列f中input数字时,分数在列e中上升,在列b中(在同一行上),颜色必须变成绿色或红色
我做了这个VBA代码,但没有运气。
Private Sub Worksheet_Change(ByVal Target As Range) If Not Intersect(Target, Range("e5:e67")) Is Nothing Then If Target.Column = 5 Then thisRow = Target.Row Dim OldValue As Variant Application.EnableEvents = False Application.Undo OldValue = Target.Value Application.Undo Application.EnableEvents = True If OldValue < Target.Value Then Range("b" & thisRow).Interior.ColorIndex = 4 ElseIf OldValue > Target.Value Then Range("b" & thisRow).Interior.ColorIndex = 3 End If End If End If End Sub
这是我的排行榜的屏幕截图:
尝试拦截Worksheet_Calculate
事件。 您需要将旧的值保存在一个static
本地数组中,我称之为oldVal
。
Private Sub Worksheet_Calculate() Static oldVal If IsEmpty(oldVal) Then oldVal = Application.Transpose(Range("e5:e67").Value2) ReDim Preserve oldVal(5 To 67) Exit Sub End If Dim i As Long For i = LBound(oldVal) To UBound(oldVal) If oldVal(i) > Cells(i, "E").Value2 Then Cells(i, "B").Interior.ColorIndex = 3 If oldVal(i) < Cells(i, "E").Value2 Then Cells(i, "B").Interior.ColorIndex = 4 oldVal(i) = Cells(i, "E").Value2 Next End Sub
Private Sub Worksheet_Change(ByVal Target As Range) Dim i As Integer If Not Intersect(Target, Range("e6:e67")) Is Nothing Then If Target.Offset(-1) < Target Then i = 4 Else i = 3 End If Range("b" & Target.Row).Interior.ColorIndex = i End If End Sub