Alt+F11,打开编辑器,按如下代码编写代码:
Sub SetGroupBg()Dim i, j, cColors = Array("#CEFFCE", "#D7FFEE", "#D9FFFF", "#C4E1FF", "#DDDDFF", "#FFDAC8", "#FFE4CA", "#FFF4C1", "#FFFFCE", "#E8FFC4")j = UsedRange.Columns.CountFor i = 2 To UsedRange.Rows.CountIf Cells(i, 1) <> Cells(i - 1, 1) Thenc = c Mod UBound(Colors) + 1clr = Application.Hex2Dec(Replace(Colors(c), "#", ""))End IfRange(Cells(i, 1), Cells(i, j)).Interior.Color = clrNext
End Sub
运行代码即可达到预期效果。
代码说明:
- 定义需要的颜色值;
- 逐行扫描内容;
- 根据每行首个单元格式内容是否相同,循环设置背景颜色。