2017-05-08 166 views
0

我正在嘗試使宏突出顯示當前單元格的整個行。我在其他地方找到了下面的代碼,雖然它突出顯示了整行,但它也從以前着色的單元格中移除顏色。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 

回答

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

這個偉大的工程!謝謝 :) – Sarchwalk

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

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