如何在excel中仅清除此代码中突出显示的先前单元格?

时间:2021-06-30 06:19:09

标签: excel

我发现此代码可以插入到 excel 中以在您单击单元格后突出显示某些单元格。

Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

'Set the context appropriately using With...End With
With Sheets("calendar")

    'Clear all previously-applied highlighting for easy readability
    .Cells.Interior.ColorIndex = xlColorIndexNone

    'Switch on the address of the selected cell
    Select Case Target.Address
    
        Case "$A$1" '<~ if cell A1 is clicked, highlight cells C5-C9 yellow
            .Range("C5:C9").Interior.Color = RGB(255, 255, 0)
            
        Case "$A$2" '<~ if cell A2 is clicked, highlight cell D5-D9 green
            .Range("D5:D9").Interior.Color = RGB(0, 255, 0)
            
        Case "$A$3" '<~ if cell A3 is clicked, highlight cell E5-E9 orange
            .Range("E5:E9").Interior.Color = RGB(255, 165, 0)
            
    End Select
End With
End Sub

问题是它清除了工作表中的所有突出显示。我只想在不再选择所选单元格后清除突出显示。

1 个答案:

答案 0 :(得分:0)

如果您在 A2:D5 范围内执行操作,将运行以下代码。您可以根据自己的需要更改此范围。

If Not Application.Intersect(Target, Range("A2:D5")) Is Nothing Then   
    Range("C5:C9").Interior.Color = RGB(255, 255, 0)   
End If