簡體   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