对于范围中的每个单元格(如果单元格为负),则更改颜色

时间:2018-07-31 14:02:23

标签: excel vba excel-vba

我对VBA很了解,我正在尝试检查是否在M列的特定范围内是否存在负数,以及是否要将字体更改为红色。这仅适用于我的报告中的第一个数字。我感觉自己犯了个小错误,请让我知道。

Sub Format_M_Column()

    Range("M:M").Select
    With Selection
        Selection.NumberFormat = "0.00"
        .Value = .Value
    End With

    For Each cell In Range("M:M")
        If cell.Value < 0 Then
            cell.Font.ColorIndex = 3
            Exit For
        End If
    Next cell

End Sub

3 个答案:

答案 0 :(得分:1)

删除Exit For。它退出for-循环:

Excel VBA - exit for loop

答案 1 :(得分:1)

ScottCraner指出,这应该是您所需要的,并且应该快得多,而无需循环。

Sub Format_M_Column()
    With Range("M:M")
        .NumberFormat = "0.00;[Red]-0.00"
        .Value = .Value
    End With
End Sub

答案 2 :(得分:0)

尝试此代码(可能比您的速度更快)

Sub Format_M_Column()
Dim rng As Range
Dim cel As Range

Application.ScreenUpdating = False
    Set rng = Intersect(ActiveSheet.UsedRange, ActiveSheet.Columns(13))

    With rng
        .NumberFormat = "0.00"
        .Value = .Value
        For Each cel In rng
            If cel.Value < 0 Then cel.Font.ColorIndex = 3
        Next cel
    End With
Application.ScreenUpdating = True
End Sub