如何在excel中计算不同字体颜色的文本

时间:2013-04-08 19:26:25

标签: excel vba excel-vba worksheet-function

我有一个从另一个数据库导出到excel的名称列表。列表中感兴趣的名称以红色字体突出显示。我想要一种计算它的方法,即约翰史密斯在一列中总共出现5次,但在5次中出现3次,他的名字以红色字体突出显示。所以我想看看他的名字中有多少个出现红色。

我知道如何搜索他名字的所有实例,例如= COUNTIF(A1:A100,“John Smith”)

我还帮助创建了一个VB函数,该函数使用以下函数计算工作表中所有红色值(= SumRed)(一旦指定了颜色索引):

Function SumRed(MyRange As Range)
    SumRed = 0
For Each cell In MyRange
    If cell.Font.Color = 255 Then
        SumRed = SumRed + cell.Value
    End If
Next cell
End Function

我找不到结合两种计数条件的方法。任何帮助将不胜感激!

3 个答案:

答案 0 :(得分:15)

您不需要VBA,但如果您想要VBA解决方案,那么您可以使用其他任何一个答案。 :)

我们可以使用Excel公式查找单元格的字体颜色。见这个例子。

我们将使用XL4宏。

  1. 打开名称管理器
  2. 给出一个名字。说FontColor
  3. 在引用=GET.CELL(24,OFFSET(INDIRECT("RC",FALSE),0,-1))中输入此公式,然后单击确定
  4. enter image description here

    公式说明

    语法是

    GET.CELL(type_num, reference)
    
    Type_num is a number that specifies what type of cell information you want.
    reference is the cell reference
    

    在上面的公式中,数字24为您提供单元格中第一个字符的字体颜色,为1到56范围内的数字。如果字体颜色为自动,则返回0. 和因此缺点。确保整个字体颜色为红色。我们本可以使用64但这样做不正常。

    OFFSET(INDIRECT("RC",FALSE),0,-1)指的是左侧的直接单元格。

    现在在单元格=IF(AND(Fontcolor=3,B1="John Smith"),1,0)中输入此公式并将其复制下来。

    注意:必须在包含文本的单元格的右侧输入公式。

    <强> Screentshot

    enter image description here

    编辑(2013年10月12日)

    要计算具有特定背景色的单元格,请参阅THIS链接

答案 1 :(得分:2)

我认为你几乎就在那里,但这应该是@user打赌我的另一个功能:(

Function CoundRedAndText(MyRange As Range, Mytext as string) as long
    CoundRedAndText = 0
    For Each cell In MyRange
        If cell.Font.Color = 255 and cell.value like MyText Then
            CoundRedAndText = CoundRedAndText + 1 'you had cell.value but dont know why?
        End If
    Next cell
End Function

用法,=CountRedAndText(A1:A25, "John Smith")

答案 2 :(得分:0)

For Each cell In Range("A1:A100")
    If cell.Font.Color = 255 And cell.Value = "John Smith" Then
        myCount = myCount + 1
    End If
Next