自动突出显示一行,所以原始填充保留在失去焦点

我有一个带有背景颜色的列的工作簿。 我希望突出显示一行,当select一个单元格与背景颜色的变化。

下面的代码可以做到这一点,但是当我移动到另一行时,不会恢复原始背景颜色:

Sub Worksheet_SelectionChange(ByVal Target As Excel.Range) Static rr If rr <> "" Then With Rows(rr).Interior .ColorIndex = xlNone End With End If r = Selection.Row rr = r With Rows(r).Interior .ColorIndex = 39 .Pattern = xlSolid End With End Sub 

请任何人都可以提出一种方法,我可以改变代码,以恢复原来的背景,当我继续前进?

您需要将以前的格式保存到某个位置,然后不要设置.ColorIndex = xlNone ,而是恢复以前的格式。 下面的代码通过将格式粘贴到表格的最后一行,然后执行“select性粘贴/格式”来恢复它。 不是很优雅,但确实有效。

 Private Sub Worksheet_SelectionChange(ByVal Target As Range) Static lngPrevRow As Long Dim rngActiveCell As Range On Error GoTo errorHandler 'prevent this code from triggering itself when it changes the selection Application.EnableEvents = False Application.ScreenUpdating = False 'save active cell, as messing about with copy and paste will change the active cell Set rngActiveCell = ActiveCell If lngPrevRow <> 0 Then 'paste saved format to previous row ActiveSheet.Rows(ActiveSheet.Rows.Count).Copy ActiveSheet.Rows(lngPrevRow).PasteSpecial xlPasteFormats 'save current row's format at end of sheet ActiveSheet.Rows(rngActiveCell.Row).Copy ActiveSheet.Rows(ActiveSheet.Rows.Count).PasteSpecial xlPasteFormats 'tidy up Application.CutCopyMode = False Target.Select End If lngPrevRow = rngActiveCell.Row 'highlight active row With ActiveSheet.Rows(rngActiveCell.Row).Interior .ColorIndex = 39 .Pattern = xlSolid End With Application.ScreenUpdating = True Application.EnableEvents = True Exit Sub errorHandler: 'other error handling code here... Application.ScreenUpdating = True Application.EnableEvents = True End Sub 

注意事项:

  • 总是将variables声明为一个types(例如As Long ) – 这可以防止各种细微的错误
  • 在开始时设置Application.ScreenUpdating = False可以加快速度并防止闪烁(但记得在最后将其设置为True
  • 这个(和你的原始代码一样)不能很好地处理多行select。 它可以扩展到这样做(例如通过使用Target.EntireRow而不是ActiveSheet.Rows(rngActiveCell.Row) ),但是具有额外的复杂性(您需要存储先前select的行数等等)。