基于自动字体颜色的Excel总和

Public Function ColorSum(ByVal target As range, ByVal MyColor As String) Dim Blacksum As Long, Othersum As Long, cel As range Application.Volatile Blacksum = 0 Othersum = 0 For Each cel In target If IsNumeric(cel.Value) Then If cel.Font.ColorIndex = 1 Then Blacksum = Blacksum + cel.Value Else Othersum = Othersum + cel.Value End If End If Next cel ColorSum = IIf(LCase(MyColor) = "black", Blacksum, Othersum) End Function 

我正在使用上面的代码来计算excel工作表的不同行中的黑色总和和红色总和,但是如你所知在字体选项中有一个自动黑色,当我用自动颜色(黑色)在Black总数下不加和,自动Color(黑色)单元格的总数为Red color total而不是Black color total总数,我希望自动黑色总和应该包含在黑色总和上。

我正在使用A11=colorsum(A1:A10,"black") A11=colorsum(A1:A10,"red")

xlColorIndexNone(和xlNone)是一个值为-4142的常量。

xlColorIndexAutomatic(和xlAutomatic)是一个值为-4105的常量。

使用Excel的GUI将单元格的颜色设置为“自动”将经常将ColorIndex设置为1,但如果在设置之前是另一种颜色,则将设置ColorIndex为-4105(即xlColorIndexAutomatic)。

所以我build议你检查1,xlColorIndexNone(或xlNone)和xlColorIndexAutomatic(或xlAutomatic)中的每一个。

换句话说,改变

 If cel.Font.ColorIndex = 1 Then 

 If cel.Font.ColorIndex = 1 Or _ cel.Font.ColorIndex = xlColorIndexNone Or _ cel.Font.ColorIndex = xlColorIndexAutomatic Then 

很久以前,我编程的VBA,但我认为,颜色指数= 0或xlNone或xlColorIndexAutomatic或xlColorIndexNone是自动和黑色colorIndex = 1,这是原因。 你可以尝试玩上面提到的build议值吗?

使用ColorIndex作为参考可能很困难,因为您必须记住索引。 我会build议使用color

 Function SumByFontColor(MyRange As Range, Optional MyColor As Range) Dim Rng As Range Dim Col As Long Application.Volatile If MyColor Is Nothing Then Col = Application.Caller.Font.Color Else Col = MyColor(1).Font.Color End If SumByFontColor = 0 For Each Rng In MyRange If Rng.Font.Color = Col Then SumByFontColor = SumByFontColor + Rng.Value2 End If Next Rng End Function 

有两种方法来使用公式,我希望代码是自我解释的:

在这里输入图像说明

必须注意的是,更新单元格的颜色不会启动工作表来重新计算其公式。 因此,每次更新单元格的颜色时,都必须手动按F9键重新计算。