excel vba列值相同或差5时填充不同颜色(自动填充不须执行代码)

1。应用于J列右边所有表格(自动填充不须执行代码)
2。当倒数第二个数值与它上面7个数值对比时,相同时或者相差5时才做填充颜色
3。如果列增加销售数值,上面的颜色自动取消(任何时只保留最后第二数值与上面7数值的颜色)
http://pan.baidu.com/s/1pJr8Gp9

第1个回答  推荐于2016-04-02
把下面的代码复制到工作表中,不要放在模块中,这个属于工作表的私有模块,意思每次激活这个工作表就会自动运行代码
工作表标签点右键--查看代码--弹出VB窗口,把代码复制进去关闭--保存工作表

Private Sub Worksheet_Activate()
Dim x%
x = Cells(Rows.Count, "j").End(xlUp).Row
For i = x - 2 To x - 8 Step -1

If Range("j" & x - 1) = Range("j" & i) Then
Range("j" & i).Interior.ColorIndex = 3
Range("j" & x - 1).Interior.ColorIndex = 3
ElseIf Range("j" & x - 1) - Range("j" & i) = 5 Then
Range("j" & i).Interior.ColorIndex = 10
End If

Next
End Sub追问

还原颜色,再自动填充不须执行代码
J列右边所有列

追答

用下面代码试下
Private Sub Worksheet_Activate()
Columns("j:iv").Interior.ColorIndex = 0
Dim x%
For r = 10 To [iv1].End(xlToLeft).Column
x = Cells(Rows.Count, r).End(xlUp).Row
If x < 8 Then
Exit Sub
End If
For i = x - 2 To x - 8 Step -1

If Cells(x - 1, r) = Cells(i, r) Then
Cells(i, r).Interior.ColorIndex = 3
Cells(x - 1, r).Interior.ColorIndex = 3
ElseIf Cells(x - 1, r) - Cells(i, r) = 5 Or Cells(x - 1, r) - Cells(i, r) = -5 Then
Cells(i, r).Interior.ColorIndex = 10
End If
Next
Next
End Sub

本回答被提问者采纳
第2个回答  2015-05-28
Sub xx()
    n = [j65536].End(3).Row
    If n <= 9 Then Exit Sub
    [j:j].ClearFormats
    x = False
    For i = n - 9 To n - 2
        If Cells(i, "j") = Cells(n - 1, "j") Then Cells(i, "j").Interior.ColorIndex = 7: x = True
        If Abs(Cells(i, "j") - Cells(n - 1, "j")) = 5 Then Cells(i, "j").Interior.ColorIndex = 10: x = True
    Next
    If x Then Cells(i, "j").Interior.ColorIndex = 3
End Sub

追问

1.表上面有合并单元

2.J到右边所有列(J列至IV列)

3.右边的列有的列是空列是否影响或者列都是相同的名字是否也影响填充

追答

取消单元格合并再运行

相似回答