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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19309962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 23:46:41  来源:igfitidea点击:

Excel VBA Change Color Of Cell Based On Value

excelvbacolors

提问by Brent

I need some help with a function that can change the color of the cell based on if the value of the cell is equal to the value of another, currently the cell holds an =COUNT(##:##) and I need to to Change the color from red to green if that value is equal to the value in another cell.

我需要一个函数的帮助,该函数可以根据单元格的值是否等于另一个单元格的值来更改单元格的颜色,目前该单元格包含一个 =COUNT(##:##) 并且我需要如果该值等于另一个单元格中的值,则将颜色从红色更改为绿色。

With my limited knowledge of VBA and excel I came up with this

由于我对 VBA 和 excel 的了解有限,我想出了这个

Function ChangeColor(CellColor As Range)
Application.Volatile True
If CellColor = cell.Value Then ChangeColor = cell.Interior.ColorIndex = 14
End Function

I would rather not use Conditional Formatting if at all possible, but I am open to it as a last resort if needed. Thanks for all your help and for helping me with previous questions this community is great.

如果可能的话,我宁愿不使用条件格式,但如果需要,我愿意将其作为最后的手段。感谢您的所有帮助并帮助我解决以前的问题,这个社区很棒。

回答by Greg D.

I did the code below to highlight cells in a column that were the same. The conditional formatting didn't let me cascade the formula of "equal to the cell above", maybe I just didn't do that right. Anyway this worked and is easy to change around and add to it. This example could easily be changed to suit your problem.

我做了下面的代码来突出显示列中相同的单元格。条件格式没有让我级联“等于上面的单元格”的公式,也许我只是没有做对。无论如何,这很有效,并且很容易改变和添加。可以轻松更改此示例以适合您的问题。

Sub checkduplicates()
Dim Loop1 As Integer
Dim Loop1StartRow As Integer
Dim Loop1EndRow As Integer
Dim Loop1Count As Integer
Dim Current As Integer
Dim NextOne As Integer

Loop1StartRow = 4 '4 HYIDAS
Loop1EndRow = 330 '330 HYIDAS
Loop1Count = 0

For Loop1 = Loop1StartRow To Loop1EndRow
    Worksheets("HYIDAS").Activate
    Loop1Count = Loop1Count + 1
    Current = Range("H" & Loop1)
    NextOne = Range("H" & Loop1 + 1)
    If Current = NextOne Then
        Range("H" & Loop1).Interior.Color = 220
        Range("H" & Loop1 + 1).Interior.Color = 220
    End If
Next Loop1
End Sub

回答by didierdrogod

I think you just using Conditional Formatting I know of function can't change the color or you use macro

我想你只是使用条件格式我知道函数不能改变颜色或者你使用宏

If CellColor = Selection.Value Then CellColor.Interior.ColorIndex = 14

i'm so sorry that's i know

我很抱歉,我知道