设置固定范围的单元格的背景颜色

时间:2010-04-30 16:45:11

标签: excel-vba conditional-formatting vba excel

我在Excel电子表格中有VBA代码。它用于根据该单元格中的值设置单元格的字体和背景颜色。我在VBA而不是“条件格式”中这样做,因为我有超过3个条件。代码是:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim c As Range, d As Range, fc As Long, bc As Long, bf As Boolean
Set d = Intersect(Range("A:K"), Target)
If d Is Nothing Then Exit Sub
For Each c In d
    If c >= Date And c <= Date + 5 Then
        fc = 2: fb = True: bc = 3
    Else
        Select Case c
            Case "ABC"
                fc = 2: fb = True: bc = 5
            Case 1, 3, 5, 7
                fc = 2: fb = True: bc = 1
            Case "D", "E", "F"
                fc = 2: fb = True: bc = 10
            Case "1/1/2009"
                fc = 2: fb = True: bc = 45
            Case "Long string"
                fc = 3: fb = True: bc = 1
            Case Else
                fc = 1: fb = False: bc = xlNone
        End Select
    End If
    c.Font.ColorIndex = fc
    c.Font.Bold = fb
    c.Interior.ColorIndex = bc
    c.Range("A1:D1").Interior.ColorIndex = bc
Next
End Sub

问题在于“c.Range”行。它总是使用当前单元格作为“A”,然后向右移动四个单元格。我希望它从当前行的“真实”单元格“A”开始,然后转到当前行的“真实”单元格“D”。基本上,我想要一个固定的范围,而不是一个动态范围。

1 个答案:

答案 0 :(得分:3)

所以c.Range("A1:D1")有自己的相对范围 一种解决方案是使用工作表的范围属性 我在顶部添加了两行(#added),并在底部更改了一行(#changed)。

Private Sub Worksheet_Change(ByVal Target As Range)
Dim c As Range, d As Range, fc As Long, bc As Long, bf As Boolean
Dim ws As Worksheet ''#added

Set d = Intersect(Range("A:K"), Target).Cells
Set ws = d.Worksheet ''#added
If d Is Nothing Then Exit Sub
For Each c In d.Cells
    If c >= Date And c <= Date + 5 Then
        fc = 2: bf = True: bc = 3
    Else
        Select Case c.Value
            Case "ABC"
                fc = 2: bf = True: bc = 5
            Case 1, 3, 5, 7
                fc = 2: bf = True: bc = 1
            Case "D", "E", "F"
                fc = 2: bf = True: bc = 10
            Case "1/1/2009"
                fc = 2: bf = True: bc = 45
            Case "Long string"
                fc = 3: bf = True: bc = 1
            Case Else
                fc = 1: bf = False: bc = xlNone
        End Select
    End If
    c.Font.ColorIndex = fc
    c.Font.Bold = bf
    c.Interior.ColorIndex = bc
    ws.Cells(c.Row, 1).Interior.ColorIndex = bc ''#changed
    ws.Cells(c.Row, 2).Interior.ColorIndex = bc ''#added
    ws.Cells(c.Row, 3).Interior.ColorIndex = bc ''#added
    ws.Cells(c.Row, 4).Interior.ColorIndex = bc ''#added
Next
End Sub