2017-06-03 46 views
1

我有一個電子表格,其中實現了評分板。 我需要的行爲是當具有分數值的單元格在列b附近的單元格上升時,將它的顏色更改爲綠色,當單元格分數值下降到靠近它的單元格時,它將顏色更改爲紅色。VBA從單元格更改前保存值

的單元格範圍,其中所述得分變化是E5:E67

簡而言之: 當用戶輸入F列的數,得分提高列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 

這裏是我的排名表的屏幕截圖:enter image description here

+0

當我在單元格中輸入一些F5 E5上的得分提高,但B5單元格不改變顏色爲綠色。 –

+0

啊好的。在通過公式更改值的目標上未觸發更改事件。你需要使用'Worksheet_Calculate'事件。 –

+0

在單元格e5中,我有一個公式,當用戶在單元格f5中輸入一個數字時,它的值增加10個點。如果用戶輸入1個單元格e5增長10個點,如果用戶輸入2個單元格e5增長20個點。 –

回答

0

嘗試攔截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 
+1

非常感謝您的幫助,根據您的示例,我能夠實現我需要的完整代碼,現在我的vba宏運行良好。我會標記你的答案是正確的。 –

+0

@AndréCastro歡迎您。 –

0
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 
相關問題