[英]VBA save value from cell before it changes
I have a spreadsheet where i implement a score board. 我有一个电子表格,其中装有计分板。 The behavior i need is when the cell that has the score value rises the cell near it, on column b, changes it's color to green, when the the cell score value goes down the cell near it changes it's color to red. 我需要的行为是,当具有得分值的单元格上升到它附近的单元格时,在b列上,将其颜色更改为绿色,当该单元格得分值下降时,它附近的单元格将其颜色更改为红色。
The cell range where the score is changing is e5:e67 分数变化的单元格范围是e5:e67
In short: When the user inputs a number in column f, the score raises in column e, and in column b (on same row) the color must change to green or red 简而言之:当用户在f列中输入数字时,分数在e列中升高,在b列(同一行中),颜色必须变为绿色或红色
I made this VBA code, but without luck. 我做了这个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
Try by intercepting the Worksheet_Calculate
event. 尝试通过拦截Worksheet_Calculate
事件。 You need to save the old value in a static
local array, that I call oldVal
. 您需要将旧值保存在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.