首页 文章

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

提问于
浏览
0

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

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

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

3 回答

  • 1

    这就是我能想到的:

    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 .

  • 1

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

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

    这会将突出显示之前的退出格式和行号存储到同一工作表上的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
    

相关问题