3

我在 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”。基本上,我想要一个固定范围而不是动态范围。

4

1 回答 1

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
于 2010-04-30T18:28:26.210 回答