Search code examples
excelvbacolorscell

Remove Cell color when cell color is created with a Macro Code


I created a Macro to change a cell to yellow when a change is made (top Macro). I now want to create a code so I can create a button to click to remove all of the yellow that was created with the top Macro.

I was able to find the bottom code which does turn manually highlighted cells from yellow back to white but not cells turned yellow from my Top Macro.

Below are the formats I used:

To create the Yellow Color when a change is made:

'Highlight cells yellow if change occurs

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)

If Target.Cells.Count > 1 Then Exit Sub
    Target.Interior.ColorIndex = 6
End Sub

To Remove Yellow Highlight (only works for Manual change- not the Macro)

Sub RemoveYellowFillColor()
Dim cell As Range

'Optimize Code
Application.ScreenUpdating = False

'Ensure Cell Range Is Selected
If TypeName(Selection) <> "Range" Then
MsgBox ("A2:Z1000")
Exit Sub
End If

'Loop Through Each Cell
For Each cell In Selection.Cells
If cell.Interior.Color = vbYellow Then
  cell.Interior.Color = xlNone
End If
Next

End Sub

Solution

  • This is Rev. 1 of my answer:

    As noted in comments, change from Target.Interior.ColorIndex = 6 to Target.Interior.ColorIndex = vbYellow in Workbook_SheetChange.

    Then update your macro as follows:

    Sub RemoveYellowFillColor()
    Dim ws As Worksheet, cell As Range
    
    'Optimize Code
    Application.ScreenUpdating = False
    
    'Loop Through Each Cell
    For Each ws In Worksheets
    For Each cell In ws.UsedRange.Cells
    If cell.Interior.Color = vbYellow Then cell.Interior.Color = xlNone
    Next cell
    Next ws
    
    Application.ScreenUpdating = True
    End Sub
    

    After running this macro, vbYellow fill will be removed from all cells on all worksheets in the workbook.