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")
最佳答案
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
关于vba - 基于自动字体颜色的Excel总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38417607/