0

*强文本* 下面的代码运行成功,但是,我需要一个将正单元格值和负单元格值视为相同并相应着色的代码

前任:

1) 0 到 4 和 0 到 -4 = 绿色 2) 5 到 9 和 -5 到 -9 = 橙色

以下代码仅适用于正值

子 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

结束子

4

1 回答 1

1

使用绝对值。
将条件替换(ActiveCell.Value) <= 4)(Abs(ActiveCell.Value) <= 4).

当您不使用“选择”时,这样的代码会运行得更快,只需直接引用单元格即可。

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

顺便说一句,看看Conditional Formatting

于 2013-09-06T09:23:09.853 回答