
Excel實現(xiàn)按指定的單元格顏色進(jìn)行計數(shù)或求和實例教程
如果Excel工作表的某區(qū)域中包含不同的底紋顏色,我們可以用一個自定義函數(shù)對該區(qū)域按指定的單元格顏色進(jìn)行計數(shù)或求和。方法是:
1.按Alt+F11,打開VBA器。
2.單擊菜單“插入→模塊”,將插入名稱為“模塊1”的模塊,在右側(cè)的代碼窗口中輸入下列代碼:
Function SumByColor(Ref_color As Range, Sum_range As Range)Application.VolatileDim iCol As IntegerDim rCell As RangeiCol = Ref_color.Interior.ColorIndexFor Each rCell In Sum_rangeIf iCol = rCell.Interior.ColorIndex ThenSumByColor = SumByColor + rCell.ValueEnd IfNext rCellEnd Function
Function CountByColor(Ref_color As Range, CountRange As Range)Application.VolatileDim iCol As IntegerDim rCell As RangeiCol = Ref_color.Interior.ColorIndexFor Each rCell In CountRangeIf iCol = rCell.Interior.ColorIndex ThenCountByColor = CountByColor + 1End IfNext rCellEnd Function
上述兩個自定義函數(shù),一個是SumByColor,可以對區(qū)域按指定單元格的顏色求和。另一個是CountByColor,可以統(tǒng)計區(qū)域中某種顏色的個數(shù)。這兩個自定義函數(shù)都有兩個參數(shù),前一個參數(shù)指定包含某種顏色的單元格,后一個參數(shù)為求和或計數(shù)區(qū)域。
3.關(guān)閉VBA器。
使用方法:假如要求和或計數(shù)的區(qū)域在A1:B10區(qū)域中。
求出該區(qū)域中單元格底紋顏色為紅色的所有單元格數(shù)值之和,在單元格中輸入公式:
=sumByColor(A1,A1:B10)
求出該區(qū)域中單元格底紋顏色為紅色的所有單元格的個數(shù),在單元格中輸入公式:
=CountByColor(A1,A1:B10)

