如何修改此代码,以便不是仅将与rColor
相同的彩色单元格相加,而是根据rColor
和单元格中的文本求和?
例如,将包含文本"诺基亚"。
的所有黄色单元格相加 Function ColorFunction(rColor As Range, rRange As Range, Optional SUM As Boolean)
Dim rCell As Range
Dim lCol As Long
Dim vResult
lCol = rColor.Interior.ColorIndex
If SUM = True Then
For Each rCell In rRange
If rCell.Interior.ColorIndex = lCol Then
vResult = WorksheetFunction.SUM(rCell, vResult)
End If
Next rCell
Else
For Each rCell In rRange
If rCell.Interior.ColorIndex = lCol Then
vResult = 1 + vResult
End If
Next rCell
End If
ColorFunction = vResult
End Function
我有这个表,我希望红色单元格返回2000而不是3000,而不是总结3个黄色单元格,我希望它将两个黄色的诺基亚单元格相加。
答案 0 :(得分:1)
Function ColorFunction(rColor As Range, rRange As Range, Optional SUM As Boolean, Optional valToSumOn As String)
Dim rCell As Range
Dim lCol As Long
Dim vResult
lCol = rColor.Interior.ColorIndex '6 is yellow
If SUM = True Then
For Each rCell In rRange
If rCell.Interior.ColorIndex = lCol And (Cells(rCell.Row, rCell.Column - 1).Text = valToSumOn Or valToSumOn = "") Then
vResult = WorksheetFunction.SUM(rCell, vResult)
End If
Next rCell
Else
For Each rCell In rRange
If rCell.Interior.ColorIndex = lCol And (Cells(rCell.Row, rCell.Column - 1).Text = valToSumOn Or valToSumOn = "") Then
vResult = 1 + vResult
End If
Next rCell
End If
ColorFunction = vResult
End Function
由于我修改了函数以包含文本的可选参数... sum单元格的公式现在为=colorfunction(E4,F4:F10,TRUE,"Nokia")
我添加了一个可选参数来定义要在sum列之前的列中查找的文本。 然后我检查是否设置了这个值。如果它与我们即将总和的数量相匹配,则将其添加到某些数量,否则它会跳过它。但是,如果没有设置文本,它只会将所有匹配的颜色相加。