如何使用VBA格式化生成的报告的输出

时间:2014-05-04 17:36:01

标签: excel-vba vba excel

我已经编写了VBA代码来为15以上的任何数字着色,但它显示15以上的行为红色,包括其他行。 以下是VBA代码

Sub FillCells()Dim lRow As Long, lColumn As Long
'Using Cells property to refer to range
'Loop through rows
For lRow = 1 To 10
'Loop through columns
For lColumn = 1 To 5
Cells(lRow, lColumn).Value = lRow * lColumn
Next lColumn
Next lRow
Call ColorCells
End Sub

Sub ColorCells()Dim rng As Range
Dim lRow As Long, lColumn As Long
Set rng = Range("A1:E10")
For lRow = 1 To rng.Rows.Count
For lColumn = 1 To rng.Columns.Count


If rng.Cells(lRow, lColumn).Value > 15 Then
rng.Cells(lRow, lColumn).Font.ColorIndex = 3
Else
rng.Cells(lRow, lColumn).Font.ColorIndex = 1
End If
Next lColumn
Next lRow
End Sub

将输出显示为

enter image description here

但我的问题是如何只获得15以上的红色

更新

根据此rejected edit,所需的输出为:

enter image description here

1 个答案:

答案 0 :(得分:0)

<强> UPD:

Sub ColorCells()
    Dim rng As Range, rw As Range, c As Range
    Dim rngToDel As Range

    Set rng = Range("A1:E10")
    For Each rw In rng.Rows
        If Application.CountIf(rw, ">" & 15) > 0 Then
            For Each c In rw.Cells
                If c.Value > 15 Then
                    c.Font.ColorIndex = 3
                Else
                    c.Font.ColorIndex = 1
                End If
            Next c
        Else
            If rngToDel Is Nothing Then
                Set rngToDel = rw
            Else
                Set rngToDel = Union(rngToDel, rw)
            End If
        End If
    Next

    If Not rngToDel Is Nothing Then rngToDel.EntireRow.Delete
End Sub

<强>结果:

enter image description here