繁体   English   中英

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

[英]How to alter the color of cells if they are a certain other 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

这可能很简单,但是我需要问一下。

DisplayFormat是只读的。 如果要更改属性,则需要删除DisplayFormat 另外,如果您正在使用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

您只需要在VBA中Set对象变量,您的if语句也有问题。 尝试:

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