2015-06-28 19 views
0

我需要一种方法来对具有相同背景色的工作表中的交替行对进行格式设置。当环顾四周,我发现下面的链接:背景格式化电子表格中的行对

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 

回答

1

尝试在条件格式这些式>使用公式来确定格式化哪个小区的:

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

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

两者都适用于$ A:$ T

将特定格式化单元格的规则放在这些一般规则之后。

希望这会有所帮助。

1

在条件格式化使用公式

=Mod(Row(),4) < 2 

你想要的规则适用于细胞

+0

(+1)的一个小的修改,因为OP请求的格式与4'排发车= AND(MOD(ROW(),4)< 2,ROW()> 3)' – Clif

+1

我明白你的意思了,我认为在第4行开始格式化的规定将由OP在决定应用哪些单元格格式化为。毕竟,如果规则没有明确地反映列间在A和T之间的规定,为什么它应该明确地反映它从第4行开始的规定?另一方面,它*更容易选择由整列组成的范围,而不是从第4行开始的范围(除非你用ctrl + shift +向下箭头流畅),所以你的修改可能会使它更方便。 –

+0

如果电子表格是完整的成对行,但修改将非常有用,但其中一个皱纹是电子表格中的行有时用作标题。使用条件格式将要求我通过,突出显示一个范围,并重新应用格式,所以= Mod(Row(),4)<2看起来并不需要。迄今为止,结果比我自己能够做的更好。谢谢克利夫和约翰科尔曼。 –