* 强文 *以下代码成功运行,但是,我需要一个代码,将正面和负面单元格值视为相同并相应地对其进行着色
前:
1)0到4和0到-4 =绿色 2)5至9和-5至-9 =橙色
以下代码仅适用于正值
Sub changeTextColor()
GreenColor = RGB(0, 128, 0)
RedColor = RGB(255, 0, 0)
OrangeColor = RGB(255, 204, 0)
WhiteColor = RGB(255, 255, 255)
'Get number of rows in the specified column
RowsCount = Range("K2", Range("K2").End(xlDown)).Rows.Count
'Select cell
Range("K2").Select
'Loop the cells
For x = 1 To RowsCount
If ((ActiveCell.Value) <= 4) Then
ActiveCell.Interior.Color = GreenColor
ElseIf ((ActiveCell.Value) >= 5) And ((ActiveCell.Value) <= 9) Then
ActiveCell.Interior.Color = OrangeColor
ElseIf ((ActiveCell.Value) > 10) And ((ActiveCell.Value) <= 10000) Then
ActiveCell.Interior.Color = RedColor
End If
ActiveCell.Offset(1, 0).Select
Next
End Sub
答案 0 :(得分:1)
使用绝对值
将(ActiveCell.Value) <= 4)
等条件替换为(Abs(ActiveCell.Value) <= 4)
。
当您不使用&#39; Select&#39;时,这样的代码将运行得更快,只需直接引用单元格。
Dim v As Long
Dim r As Range
Dim i As Long
' [...]
'Select cell -> NO, don't
' Range("K2").Select
'Loop the cells
For x = 1 To RowsCount
Set r = ActiveSheet.Cells(1+x, "K") ' starts at K2
v = Abs(r.Value)
If v <= 4 Then
r.Interior.Color = GreenColor
elseif ... ' and so on
' ...
Next
顺便说一下,看看条件格式。