我有一个包含背景颜色的列的工作簿。我希望在选择背景颜色变化的单元格时突出显示一行。
以下代码可以正常工作,但在移动到另一行时不会恢复原始背景颜色:
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
当我继续前进时,是否有人可以建议我可以改变代码以恢复原始背景的方式?
答案 0 :(得分:1)
您需要在某处保存以前的格式,然后恢复以前的格式,而不是设置.ColorIndex = xlNone
。下面的代码的工作方式是将格式粘贴到工作表的最后一行,然后执行选择性粘贴/格式以恢复它。不是很优雅,但确实有效。
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
注意事项:
As Long
) - 这可以防止各种细微错误Application.ScreenUpdating = False
可以加快速度并防止闪烁(但请记住最后将其设置回True
)Target.EntireRow
而不是ActiveSheet.Rows(rngActiveCell.Row)
),但具有额外的复杂性(您需要存储先前选择的行数等,等等)。