excel 里如何用宏 根据 某个单元格的颜色,设置这个单元格左右五个单元格的颜色?

如图,运行宏之前只有绿色单元格里面是绿色的,运行宏之后,绿色单元格左右两边的单元格也都变成绿色了!
图片里面只是举例,一个表格里面的单元格颜色可能有很多种,我要的是运行宏后,带颜色的单元格左右两边都变成个颜色单元格一样的颜色! (不好意思,有点绕口!)

Cells(4, 6).Offset(0, 1).Interior.Color = Cells(4, 6).Interior.Color
上面VBA执行后则将(4,6)单元格的颜色向右偏移一格填充(4,6)颜色
将(0,1)换成(0,-1)则是向左偏移填充颜色

执行下面的宏代码

Sub a()
For i = 2 To 100 '假设有99行要涂色的数据
If Cells(i, 3) <> "" Then
Cells(i, 3).Offset(0, 1).Interior.Color = Cells(i, 3).Interior.Color '向右的一个单元格填充颜色
Cells(i, 3).Offset(0, 2).Interior.Color = Cells(i, 3).Interior.Color '向右的第二个单元格填充颜色
Cells(i, 3).Offset(0, -1).Interior.Color = Cells(i, 3).Interior.Color '向左的一个单元格填充颜色
Cells(i, 3).Offset(0, -2).Interior.Color = Cells(i, 3).Interior.Color '向左的第二个单元格填充颜色
End If
Next
End Sub
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-12-13
我写了一个,请试用下。
请在执行宏之前,选中那个基准单元格(就是以这个单元格为基准,把它的颜色向左向右扩展的)。当左边不足5个单元格时,就到第1个为止。

Sub FillBackground()
Dim background, myCell As Range, theRow As Long
Dim startCell As Integer, endCell As Integer
Set myCell = ActiveCell
theRow = myCell.Row()
background = myCell.Interior.Color
startCell = myCell.Column() - 5
If startCell < 1 Then startCell = 1
endCell = myCell.Column() + 5
Range(Cells(theRow, startCell), Cells(theRow, endCell)).Interior.Color = background
myCell.Offset(1, 0).Range("A1").Select '选中下一行同列单元格
End Sub

GoodLuck!
相似回答