在Excel中交替显示行的着色组

时间:2020-03-05 18:43:03  来源:igfitidea点击:

我有一个这样的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代码

谢谢

解决方案

回答

如果在"格式"菜单项下选择"条件格式"菜单选项,将显示一个对话框,让我们构造一些逻辑以应用于该单元格。

逻辑可能与上面的代码不同,看起来可能更像:

单元格值为|等于| |和|白色....然后选择颜色。

我们可以选择添加按钮,并根据需要设置条件。

回答

我们必须使用代码吗?
如果表是静态的,那为什么不使用自动格式化功能呢?

如果我们"合并"相同数据的单元格也可能会有所帮助。因此,如果将"数据,更多数据,甚至更多数据"的单元格合并到一个单元格中,则可以更轻松地处理经典的"每一行都是一行"的情况。

回答

我认为这可以满足需求。当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