简体   繁体   English

如果细胞是某种其他颜色,如何更改它们的颜色?

[英]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 我已经使用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. DisplayFormat是只读的。 If you want to change the property, you need to drop DisplayFormat . 如果要更改属性,则需要删除DisplayFormat Also, if you are using For each Cell , then you should refer to Cell , not ActiveCell . 另外,如果您正在使用For each Cell ,则应该引用Cell而不是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. 您只需要在VBA中Set对象变量,您的if语句也有问题。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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