简体   繁体   English

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

[英]Change the value of a cell in Excel based on cell color

I am using the following VBA code to change the value of cells based on their color but it changes all selected cells including colored cells. 我正在使用以下VBA代码根据其颜色更改单元格的值,但是它将更改所有选定的单元格,包括彩色单元格。 Please help me in this regard:- 请在这方面帮助我:

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

The issue you are having is that both a cell with no/unset/default * background colour and a cell with a background colour explicitly set to white have the same .Interior.Color property value ( 16777215 ). 您遇到的问题是,没有/未设置/默认*背景色的单元格和具有明确设置为白色的背景色的单元格都具有相同的 .Interior.Color属性值( 16777215 )。

To distinguish the two, you need to check each cell's .Interior.ColorIndex property instead. 为了区分两者,您需要检查每个单元格的.Interior.ColorIndex属性。 A cell with no background colour has .Interior.ColorIndex equal to xlNone ( -4142 ) whilst a cell with a set white background colour has .Interior.ColorIndex equal to 2 . 没有背景色的单元格具有.Interior.ColorIndex等于xlNone-4142 ),而具有白色背景色的单元格具有.Interior.ColorIndex等于2

Thus, your code needs to be changed to the following to correctly set the value of the "white" coloured cells to OFF : 因此,您的代码需要更改为以下内容,才能将“白色”彩色单元格的值正确设置为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

Note: 注意:
* If your default background colour is not white, the .Interior.Color property value is still white. *如果您的默认背景颜色不是白色,则.Interior.Color属性值仍为白色。 This is because the only way to "change" the default cell colour is by adding a coloured background image. 这是因为“更改”默认单元格颜色的唯一方法是添加彩色背景图像。 The underlying cell's background colour remains unset. 基础单元格的背景颜色保持不变。

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

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