VBA COUNTIF的字体颜色

时间:2018-02-07 21:00:54

标签: excel vba

我希望创建一个COUNTIF,它考虑了条件字符串的文本值和字体颜色。这就是我到目前为止所提出的。它目前正在返回#VALUE!错误。

Function test(range As range, criteria As range) As Double

Dim cell As range
Dim criteriaLength As Integer
Dim counter As Integer

counter = 0

For Each cell In range
    If InStr(cell.value, criteria.value) > 0 And 
    cell.Characters(InStr(cell.value, criteria.value), 
    criteriaLength).Font.Color = criteria.Font.Color Then
         counter = counter + 1
    End If
Next cell
test = counter

End Function

搜索范围中的单元格都包含不同字体颜色的字符 - 这就是我使用InStr和字符的原因。任何想法可能是什么问题?

1 个答案:

答案 0 :(得分:1)

您永远不会为criteriaLength

指定值

您需要添加:

criteriaLength = Len(criteria)
在循环之前

并且If将尝试在if中的And的两侧,如果条件不在字符串中,则第二部分将出错。你需要嵌套if if,如果第一个返回True,第二个只会触发。

Function test(range As range, criteria As range) As Double

Dim cell As range
Dim criteriaLength As Integer
Dim counter As Integer

counter = 0
criteriaLength = Len(criteria)
For Each cell In range
    If InStr(cell.Value, criteria.Value) > 0 Then
        If cell.Characters(InStr(cell.Value, criteria.Value), criteriaLength).Font.color = criteria.Font.color Then
            counter = counter + 1
        End If
    End If
Next cell
test = counter

End Function