如果Cell.Value>(大于)函数无法为单元格着色

时间:2019-03-19 22:38:55

标签: excel vba

我当前正在使用的代码。

Dim iRowCq As Range
Set iRowCq = Range("B2:DJ26")

For Each Cell In iRowCq

    If Cell.Value > "0.3" or cell.value > 0.3 Then
        Cell.Interior.Color = RGB(0, 255, 0)
    End If

Next

我想给大于0.3的绿色单元格上色。然而,尽管99%的单元格都可以工作,但有时仍有一些单元格大于0.3且没有着色。香港专业教育学院甚至试图将数据四舍五入到两个小数点之前不起作用。有人可以帮忙吗?

Screen shot of excel sheet

3 个答案:

答案 0 :(得分:1)

您不能将字符串比较和数字比较相结合,例如,大于/小于比较。字符串可能不大于"0.3"作为字符串,但总会被排序为大于0.3作为数字。`组合字符串和数值比较可能严格地等于等于< / em>基础。

采用字符串或带整数的数值并将其用于比较。

Dim iRowCq As Range Set iRowCq = Range("B2:DJ26")

For Each Cell In iRowCq

    If val(Cell.Value) > 0.3 Then
         Cell.Interior.Color = RGB(0, 255, 0)
    End If

Next

答案 1 :(得分:1)

您为什么要重新发明条件格式?可以通过非常简单的方式完成,而无需VBA:

enter image description here

答案 2 :(得分:0)

您可以尝试以下操作:

Option Explicit

Sub test1()

    Dim rng As Range, cell As Range

    With ThisWorkbook.Worksheets("Sheet1") '<- It s better practise to specify the worksheet

        Set rng = .Range("B2:DJ26") '<- This range does not cover your whole spreadsheet. As i can see from the image the last column IS NOT "D" BUT "S" and the last row IS NOT 26 BUT 25. Setting range to *.Range("B2:SJ25")* we cover your range.

        For Each cell In rng

            If CDec(cell.Value) > 0.3 Then '<- Convert the cell value into decimal in order to compare with decimal
                cell.Interior.Color = RGB(0, 255, 0)
            End If

        Next

    End With

End Sub