VBA突出显示当前行没有删除所有单元格颜色

时间:2017-05-08 17:37:14

标签: excel vba excel-vba

我正在尝试创建一个宏来突出显示当前单元格的整行。我在其他地方找到了下面的代码,虽然它突出显示整行但它也删除了以前任何彩色单元格的颜色。

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

我希望找到的是一段允许修改先前选择的单元格/行的代码。我是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

4 个答案:

答案 0 :(得分:1)

您需要在某处存储格式和行号,然后在选择新行时将其粘贴回来。

这会将突出显示之前的退出格式和行号存储到同一张纸上的1,040,000行。

然后当选择另一行时,它将检查那里是否有格式化并替换它被复制回来的行。

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

答案 1 :(得分:1)

条件格式覆盖&#34;常规&#34;格式化(不替换它),因此如果您还没有应用某些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

答案 2 :(得分:0)

这是我能想到的:

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

答案 3 :(得分:0)

我为此创建了一个add-in。下载并启用内容,然后单击安装按钮。加载项在“视图”功能区选项卡上创建三个按钮,用于切换突出显示。

  • 使用条件格式,因此没有替代的单元格颜色设置。
  • 所有代码都在外接程序中,因此不需要其他VBA。

enter image description here

相关问题