如果Excel工作表的某區(qū)域中包含不同的底紋顏色,我們可以用一個自定義函數(shù)對該區(qū)域按指定的單元格顏色進行計數(shù)或求和。方法是:
1.按Alt+F11,打開VBA編輯器。
2.單擊菜單“插入→模塊”,將插入名稱為“模塊1”的模塊,在右側(cè)的代碼窗口中輸入下列代碼:
Function SumByColor(Ref_color As Range, Sum_range As Range)
Application.Volatile
Dim iCol As Integer
Dim rCell As Range
iCol = Ref_color.Interior.ColorIndex
For Each rCell In Sum_range
If iCol = rCell.Interior.ColorIndex Then
SumByColor = SumByColor + rCell.Value
End If
Next rCell
End Function
Function CountByColor(Ref_color As Range, CountRange As Range)
Application.Volatile
Dim iCol As Integer
Dim rCell As Range
iCol = Ref_color.Interior.ColorIndex
For Each rCell In CountRange
If iCol = rCell.Interior.ColorIndex Then
CountByColor = CountByColor + 1
End If
Next rCell
End 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)