简体   繁体   中英

How to alter the color of cells if they are a certain other color?

I have written a short Macro to change cells of a given colour to another colour in a workbook. This code throws no errors however it simply does nothing.

I have already tested the colour codes to see if they are correct using MsgBox ActiveCell.DisplayFormat.Interior.color

Option Explicit

Sub Recolour()
    Application.ScreenUpdating = False
    Dim Sheet As Worksheet
    Dim Rng As Range
    Dim OldColour As Variant
    Dim NewColour As Variant
    Dim Cell As Range

    Set Rng = ActiveSheet.Range("A1:Y457")
    OldColour = 128
    NewColour = RGB(134, 38, 51)

    For Each Sheet In ThisWorkbook.Worksheets

        For Each Cell In Rng.Cells

            If ActiveCell.DisplayFormat.Interior.Color = OldColour _
                Then _
                Set ActiveCell.DisplayFormat.Interior.Color = NewColour _
            Else

        Next Cell

    Next Sheet

    Application.ScreenUpdating = True

End Sub

This is probably something simple and daft however I need to ask.

DisplayFormat is read-only. If you want to change the property, you need to drop DisplayFormat . Also, if you are using For each Cell , then you should refer to Cell , not ActiveCell .

For Each Sheet In ThisWorkbook.Worksheets
    For Each Cell In Rng.Cells
        If Cell.Interior.color = OldColour Then 
            Cell.Interior.color = NewColour
        End if    
    Next Cell
Next Sheet

You only need to Set object variables in VBA, your if statement is also problematic. Try:

For Each Sheet In ThisWorkbook.Worksheets
    For Each Cell In Rng.Cells
        If ActiveCell.DisplayFormat.Interior.color = OldColour Then 
            ActiveCell.DisplayFormat.Interior.color = NewColour
        End if    
    Next Cell
Next Sheet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM