我写了一个简短的宏,将工作簿中给定颜色的单元格更改为另一种颜色。这段代码不会引发任何错误,但是它什么也不做。
我已经测试了颜色代码,以使用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
这可能很简单,但是我需要问一下。
答案 0 :(得分:0)
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
答案 1 :(得分:-1)
您只需要在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