Excel中有一系列单元格需要用字体颜色求和。
A栏只是供应商的名字,显然是5月的整个月份:
理想情况下,我想知道此范围内黑色,红色或蓝色细胞的总和 所以我开发了两个场景,一个有和没有宏。
在红色和黑色单元格中添加一个字符串,以确定它们是“不同的” 例如。改变268至268c和66.5至66.5u但保持52.96不变
使用下面的数组公式:
{=SUM(IF(ISNUMBER(B7:C16),B7:C16,NUMBERVALUE(LEFT(B7:C16,3))))}
这会跳过66.5中的.5但是有效,一旦我将LEFT
函数中的3(将单元格从文本截断为字符串)更改为LEN(B6:C17)-1
,它就不起作用
插入模块并创建此公式,该公式可独立运行:
Function GetCellColor(ByVal Target As Range) As Integer
GetCellColor = Target.Font.ColorIndex
End Function
使用下面的公式(如果是数组公式则给出错误):
=SUM(IF(getcellcolor(B7:C16)=3,B7:C16,0))
*我可以手动编写遍历每个单元格的代码并添加,但我想知道每个场景的问题是什么......
答案 0 :(得分:0)
您不能在多个单元格的范围内执行Target.Font.ColorIndex
。使用更大的范围将产生null
。
您可以在UDF中传递范围和循环求和。另外,将颜色作为参数传递给函数。
单色:
Public Function GetCellColor(ByRef Target As Range, ByVal targetColour As Long) As Long
Dim outValue As Long, currentcell As Range
For Each currentcell In Target.Cells
If currentcell.Font.ColorIndex = targetColour Then outValue = outValue + currentCell
Next currentcell
GetCellColor = outValue
End Function
最多3种颜色:
这可能需要改进,但如果使用最多3种颜色,最后2种是可选的,并且不应该多次传递单个颜色,你可以尝试类似:
Public Function GetCellColor(ByRef Target As Range, ByVal targetColour As Long, Optional ByVal targetColour2 As Variant, Optional ByVal targetColour3 As Variant) As Long
Dim outValue As Long, currentcell As Range
Select Case True
Case Not IsMissing(targetColour2) And Not IsMissing(targetColour3)
If targetColour2 = targetColour3 Or targetColour = targetColour2 Or targetColour = targetColour3 Then GoTo earlyExit
Case IsMissing(targetColour2) And Not IsMissing(targetColour3)
If targetColour = targetColour3 Then GoTo earlyExit
Case Not IsMissing(targetColour2) And IsMissing(targetColour3)
If targetColour = targetColour2 Then GoTo earlyExit
End Select
For Each currentcell In Target.Cells
If currentcell.Font.ColorIndex = targetColour Then outValue = outValue + currentcell
If Not IsMissing(targetColour2) Then
If currentcell.Font.ColorIndex = targetColour2 Then
outValue = outValue + currentcell
End If
End If
If Not IsMissing(targetColour3) Then
If currentcell.Font.ColorIndex = targetColour3 Then
outValue = outValue + currentcell
End If
End If
Next currentcell
GetCellColor = outValue
Exit Function
earlyExit:
GetCellColor = CVErr(xlErrValue)
End Function
答案 1 :(得分:0)
正如QHarr指出的那样,你无法在多小区范围内使用Font.ColorIndex
。
这是您的原始工作表函数中使用的UDF版本:
Function GetCellColor(ByVal Target As Range)
Dim arr(), r As Long, c As Long
ReDim arr(1 To Target.Rows.Count, 1 To Target.Columns.Count)
For r = 1 To UBound(arr, 1)
For c = 1 To UBound(arr, 2)
arr(r, c) = Target(r, c).Font.ColorIndex
Next
Next
GetCellColor = arr
End Function