在Excel中更新值时更改单元格的颜色

如果使用macros更新,是否有可能更改单元格的背景颜色?

我正在使用IF语句的VBA for循环更新单元格。

是否有可能在更新后更改for循环中的背景颜色?

Dim cella As Range For Each cella In Range("D15:AE15").Cells If cella.Value = 0 And cella.Offset(17).Value = 2 Then cella.Value = 1 cella.Offset(17).Value = 1 cella.Interior.ColorIndex = 3 End If Next cella 

我试过在循环内使用内部颜色索引function,但它似乎不工作? (而且我只想为更新的单元格着色)

你要找的东西是这样的:

  With cella.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .Color = 255 End With 

但是,您的代码中有一些语法错误。 我根据我所看到的做了一些假设,但是这完全是正确的:

  For Each cella In Range("A1:B15") If cella.Value = 0 And cella.Offset(17, 0).Value = 2 Then cella.Value = 1 cella.Offset(17, 0).Value = 1 'offset syntax is (rows, columns) With cella.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .Color = 255 End With End If Next cella 

在例如Sheet1的代码模块中插入一个Worksheet_change

 Private Sub Worksheet_Change(ByVal Target As Range) <your code> End sub 

Target是改变的范围(单元格)