在Excel中交替着色行组

Mar*_*Deé 11 excel vba excel-vba

我有这样的Excel电子表格

id | data for id
   | more data for id
id | data for id
id | data for id
   | more data for id
   | even more data for id
id | data for id
   | more data for id
id | data for id
id | data for id
   | more data for id

现在我想通过交替行的背景颜色来对一个id的数据进行分组

var color = white
for each row
    if the first cell is not empty and color is white
        set color to green
    if the first cell is not empty and color is green
        set color to white
    set background of row to color

任何人都可以帮助我使用宏或一些VBA代码

谢谢

Adr*_*o P 38

我使用此公式来获取条件格式的输入:

=IF(B2=B1,E1,1-E1))    [content of cell E2]
Run Code Online (Sandbox Code Playgroud)

其中B列包含需要分组的项目,E是辅助列.每当上单元(在这种情况下为B1)与当前单元(B2)相同时,返回来自列E的上行内容.否则,它将返回1减去该内容(也就是说,outupt将为0或1,具体取决于上部单元格的值).

在此输入图像描述

在此输入图像描述

在此输入图像描述

  • 很好的答案.作为MOD功能的替代,您可以使用`1 - E1`.所以完整的公式是`= IF(B2 = B1,E1,1-E1)` (6认同)
  • 在我的情况下,我不能在公式中使用分号(;),只有逗号(,)是Excel可以接受的.我正在使用MS Excel v 14.0.7106.5003 32位. (4认同)
  • 是否可以避免使用额外的列? (2认同)

Jas*_*n Z 4

我认为这正是您正在寻找的。当 A 列中的单元格更改值时翻转颜色。运行直到 B 列中没有值为止。

Public Sub HighLightRows()
    Dim i As Integer
    i = 1
    Dim c As Integer
    c = 3       'red

    Do While (Cells(i, 2) <> "")
        If (Cells(i, 1) <> "") Then    'check for new ID
            If c = 3 Then
                c = 4   'green
            Else
                c = 3   'red
            End If
        End If

        Rows(Trim(Str(i)) + ":" + Trim(Str(i))).Interior.ColorIndex = c
        i = i + 1
    Loop
End Sub
Run Code Online (Sandbox Code Playgroud)