根据单元格颜色更改Excel中单元格的值

我正在使用下面的VBA代码根据其颜色更改单元格的值,但它会更改所有选定单元格,包括彩色单元格。 请在这方面帮助我:

Sub ChangeValueBasedOnCellColor() Dim rg As Range Dim xRg As Range Set xRg = Selection.Cells Application.DisplayAlerts = False For Each rg In xRg With rg Select Case .Interior.Color Case Is = 16777215 .Value = "OFF" End Select End With Next Application.DisplayAlerts = False End Sub 

你遇到的问题是没有/ unset / default *背景颜色的单元格和背景颜色显式设置为白色的单元格都具有相同的 .Interior.Color属性值( 16777215 )。

要区分这两者,您需要检查每个单元格的.Interior.ColorIndex属性。 没有背景颜色的单元格的.Interior.ColorIndex等于xlNone-4142 ),而具有白色背景色的单元格的.Interior.ColorIndex等于2

因此,您的代码需要更改为以下正确设置“白色”单元格的值为OFF

 Sub ChangeValueBasedOnCellColor() Dim rg As Range Dim xRg As Range Set xRg = Selection.Cells Application.DisplayAlerts = False For Each rg In xRg With rg Select Case .Interior.ColorIndex Case Is = 2 .Value = "OFF" End Select End With Next Application.DisplayAlerts = False End Sub 

注意:
*如果您的默认背景颜色不是白色,则.Interior.Color属性值仍为白色。 这是因为“更改”默认单元格颜色的唯一方法是添加彩色背景图像。 底层单元的背景颜色保持未设置。