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表格的不同行中的黑色总计和红色总计,但是如您所知,当我输入具有该值的值时,字体选项中会出现自动黑色。颜色(黑色)它不总和黑色总和,自动颜色(黑色)单元格值总计变为红色总数而不是黑色总和,我希望自动黑色总和应包括在内关于黑色总计。
我正在使用
A11=colorsum(A1:A10,"black")
A11=colorsum(A1:A10,"red")
答案 0 :(得分:2)
xlColorIndexNone(和xlNone)是一个值为-4142的常量。
xlColorIndexAutomatic(和xlAutomatic)是一个值为-4105的常量。
使用Excel的GUI将单元格的颜色设置为"自动"通常会将ColorIndex设置为1但是,如果它在设置之前是另一种颜色,它会将ColorIndex设置为-4105(即xlColorIndexAutomatic)。
所以我建议你检查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
答案 1 :(得分:1)
很久以前我编写了vba,但我认为颜色索引= 0或xlNone或xlColorIndexAutomatic或xlColorIndexNone是自动的,Black有colorIndex = 1,这就是原因。你可以尝试使用上面提到的建议值吗?
答案 2 :(得分:1)
使用ColorIndex
作为参考可能很困难,因为您必须记住索引。我建议使用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
重新计算。