背景格式化电子表格中的行对

时间:2015-06-28 22:16:35

标签: excel-vba background-color vba excel

我需要一种方法来在工作表中以相同的背景颜色格式化交替的行对。环顾四周时,我找到了以下链接:

Excel VBA: Alternate Row Colors in Range

我的问题是类似的,除了不需要每隔一行自动填充背景颜色,我需要相邻的行对。例如,从我的第4行开始点A:T将填充,第5行A:T将具有相同的背景颜色,第6行和第7列A:T将没有背景颜色,第8行和第9行将共享背景颜色为第4行和第5行,重复直到电子表格结束。

我已尝试为此目的使用条件格式,但1)我无法从我的起点开始为每对行交替显示背景,2)它覆盖了几个特殊情况具有不同的背景颜色3)条件格式化不允许我手动格式化条件格式化函数格式化的任何行。

非常感谢评论者的建议(这使我走上正轨),但由于条件格式的限制,我拼凑了以下宏,允许根据我的需要格式化背景,而不会消除纠正的能力特殊情况。代码被大量评论,以帮助其他新手了解代码的含义以及修改内容以更改宏的行为。

Sub AlternateRowColors()

''PURPOSE:  To format the background color of alternating pairs of rows in a designated range of cells with values.
''          A correction to account for a possible empty row at the end of the range not having a value failing to follow the
''          desired pattern is included.
''          Example:            Column A
''                        Row 1:  Green
''                        Row 2:  Green
''                        Row 3:  No Background Color
''                        Row 3:  No Background Color
''          Repeating this pattern until the end of the used cells of a worksheet.

Dim lastUsedRow As Long                     ''Variable to hold the last row number.

lastUsedRow = Range("A200").End(xlUp).Row   ''This checks backwards from cell A200 to A1 for the last row with an entry in Column A
                                            ''and saves the row number in variable lastUsedRow. Modify this as needed for each worksheet.

If lastUsedRow Mod 2 = 0 Then               ''This block of code corrects for the second row of an entry not being highlighted at the
    lastUsedRow = lastUsedRow + 1               ''end of the worksheet if the first cell in the following row is blank.
        Else
End If

For Each cell In Range("A4:T" & lastUsedRow)    ''Sets the range of rows and columns that the background color formatting is to affect.
    If cell.Row Mod 4 = 0 Then                  ''Highlight row if the row number has a divided remainder of zero
        cell.Interior.ColorIndex = 35           ''Sets background color by using .ColorIndex instead of RGB.  Change to suit your need.
            Else
        If cell.Row Mod 4 = 1 Then              ''Highlight row if the row number has a divided remainder of 1
            cell.Interior.ColorIndex = 35       ''Sets background color by using .ColorIndex instead of RGB.  Change to suit your need.
        End If
    End If
Next cell

End Sub
''ADDITIONAL NOTES:
''NONE

2 个答案:

答案 0 :(得分:1)

在条件格式设置中尝试这些公式>使用公式确定要格式化的单元格:

  • =AND(ROW()>3,MOD(ROW(),4)=1)

  • =MOD(ROW(),4)=0

两者都适用于$ A:$ T

根据这些一般规则,为特殊格式的单元格制定规则。

希望这有帮助。

答案 1 :(得分:1)

在条件格式中使用公式

=Mod(Row(),4) < 2

在您希望将规则应用于

的单元格中
相关问题