VBA高亮当前行不删除所有单元格颜色

我正在试图突出显示当前单元格的整个行。 我在其他地方find了下面的代码,虽然它突出了整行,但它也从以前的任何颜色的单元格中移除颜色。

我想要发生的是,select一个单元格(可能已经被着色)整个行被突出显示,但是当我移动到另一行中的单元格时,以前突出显示的行将返回到其以前的颜色。

我希望find的是允许修改先前选定的单元格/行的一段代码。 我是VBA新手,所以很抱歉,如果这是超级简单的!

Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Target.Cells.Count > 1 Then Exit Sub Application.ScreenUpdating = False ' Clear the color of all the cells Target.Parent.Cells.Interior.ColorIndex = 0 With Target ' Highlight the entire row and column that contain the active cell .EntireRow.Interior.ColorIndex = 8 End With Application.ScreenUpdating = True End Sub 

条件格式会覆盖“常规”格式(无需replace),所以如果您还没有应用某个CF,则可以在不切换任何现有单元格颜色的情况下高亮显示某一行。

这是一个非常基本的例子:

 Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Target.Cells.Count > 1 Then Exit Sub Application.ScreenUpdating = False Me.Cells.FormatConditions.Delete With Target.EntireRow.FormatConditions.Add(Type:=xlExpression, _ Formula1:="=TRUE") .SetFirstPriority .Interior.Color = 65535 End With Application.ScreenUpdating = True End Sub 

您将需要在某处存储格式和行号,然后在select新行后将其粘贴回去。

这将在突出显示之前将同样纸张上1,040,000行的现有格式和行号存储起来。

然后,当选中另一行时,它将检查是否有格式化,并replace从哪里复制回来的行。

 Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Target.Cells.Count > 1 Then Exit Sub Application.ScreenUpdating = False 'test if formatting exist and copy it back to the row just left. If Cells(1040000, 1) <> "" Then Rows(1040000).Copy Rows(Cells(1040000, 1).Value).PasteSpecial Paste:=xlPasteFormats End If 'Copy formating to store Rows(Target.Row).Copy Rows(1040000).PasteSpecial Paste:=xlPasteFormats Cells(1040000, 1) = Target.Row With Target ' Highlight the entire row and column that contain the active cell .EntireRow.Interior.ColorIndex = 8 End With Application.CutCopyMode = False Application.ScreenUpdating = True End Sub 

这是我能想出的:

 Public rngPreviousColor As Range Public lngColor As Long Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Target.Cells.Count > 1 Then Exit Sub If Not rngPreviousColor Is Nothing Then rngPreviousColor.Interior.ColorIndex = lngColor End If Set rngPreviousColor = Target.EntireRow lngColor = rngPreviousColor.Interior.ColorIndex With Target .EntireRow.Interior.ColorIndex = 8 End With End Sub 

这个想法是,其他行是一个颜色的整体,我们保存该行作为范围rngPreviousColor和颜色为lngColor