首页 > 解决方案 > Excel VBA - 如果区域中的任何单元格文本被着色,则单元格中的颜色文本

问题描述

我制作了一个计算范围内红色文本单元格的函数。

Function CountRed(rngToSearch) As Long

Dim rngCel As Range

For Each rngCel In rngToSearch
    If rngCel.Font.Colorindex = 3 Then
        CountRed = CountRed + 1
    End If
Next rngCel

End Function

我现在正在尝试编写另一个函数来对某个范围内的单元格求和,如果该范围内有任何单元格的文本颜色为红色,那么结果也应该是红色的。

这是我得到的:

Function SumR(rngToSum) As Long

Dim rngCel As Range
Dim IsThereRed

IsThereRed = 0

For Each rngCel In rngToSum
    If rngCel.Font.Colorindex = 3 Then
        IsThereRed = 1
    End If
Next rngCel

SumR = Application.WorksheetFunction.Sum(Range(rngToSum))

If IsThereRed = 1 Then SumR.Font.Colorindex = 3

End Function

但我得到一个错误。有没有办法可以使用函数?

标签: excelvba

解决方案


要分配字体颜色,您需要定义一个范围来执行此操作。在这种情况下,您可以定义一个范围,您的结果 (SumR) 将显示在工作表中。

假设您的结果将在单元格 A10 中。您首先将结果放在该单元格中,然后根据需要为字体着色:

With Range("A10")
.Value2 = SumR
.Font.Color = RGB(255,0,0)
.NumberFormat = "#,##0" 'if you want to have a specific format for the number
End With

推荐阅读