根据背景颜色计算Excel中文本的实例

示例excel

需求是一段代码,它可以根据它们是否存在于有色单元格中,来计算string的实例,例如(ABC,DEF,GHK),并将结果放在下面的单元格中,如图所示。

任何人都可以请指教?

我试了一个示例代码

Sub Color() Dim varCounter As String Dim color As Integer Dim nocolor As Integer Range("E5").Select color= 0 nocolor= 0 Do Until Selection.Value = "" If Selection.Font.Color = RGB(255, 0, 0) Then color= color+ 1 Else nocolor= nocolor+ 1 End If Selection.Offset(1, 0).Select Loop Range("E47").Select Selection.Value = no Range("E48").Select Selection.Value = color End Sub 

这是一个非常简单的代码,检查文本字体是否着色,但我找不到任何检查单元格的背景颜色。

我也尝试过Excel的公式,但是那样我只能search文本和计数,它不会根据单元格的背景颜色来计数。

这是一个简单的用户定义函数。 你可以把它放在一个普通的模块中。 然后,您可以从工作簿中的任何工作表调用它:

 Public Function CountByColorAndText(rng As Excel.Range, SearchText As String, CountColored As Boolean) As Long Dim cell As Excel.Range Dim CellCount As Long For Each cell In rng If cell.Value = SearchText Then If (cell.Interior.ColorIndex = -4142 And Not CountColored) Or _ (cell.Interior.ColorIndex <> -4142 And CountColored) Then CellCount = CellCount + 1 End If End If Next cell CountByColorAndText = CellCount End Function 

它有三个参数:要评估的范围,要search的string以及是否计算着色(或未着色)单元格:

在这里输入图像描述

所以,上面E列的公式是:

 =CountByColorAndText($A$2:$A$13,$D3,FALSE) 

在F列中,除了最后一个参数CountColoredTRUE之外, CountColored是一样的。

我不写许多用户定义的函数,所以有人可能会指出问题或改进。

而不是Font.Color使用Interior.Color

再次编写代码会很好。 但是我有一个修改后的代码,如果你有兴趣去看看..我只是想知道这是不是一些commmon项目,但昨天OPZ问同样的问题….

VBA,COUNTIF,基于单元格颜色排除

BTW的INTERIOR.COLOR会告诉你一个很大的数字,这是RGB的代表,在那里你可能想要使用INTERIOR.COLORINDEX

由于您正在检查RGB格式,您可以尝试以下操作。 不过,我build议你不要使用select ,它会减慢你的代码。 你可以根据你的需要更换sheetsranges

例如

 Dim rng as Range Dim cell as Range '-- name column Set rng = Sheets(2).Cells(Sheets(2).Rows.Count, "C").End(xlUp).Row color= 0 nocolor= 0 For Each Cell In rng If Cell.InteriorColor = RGB(256,0,0) then color= color+ 1 Else nocolor= nocolor+ 1 End If Next Cell '--output Sheets(2).Range("E47").Value = nocolor Sheets(2).Range("E48").Value = color