如果Excel工作表的某區域中包含不同的底紋顏色,我們可以用一個自定義函數對該區域按指定的單元格顏色進行計數或求和。方法是:
1.按Alt+F11,打開VBA編輯器。
2.單擊菜單“插入→模塊”,將插入名稱為“模塊1”的模塊,在右側的代碼窗口中輸入下列代碼:
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
上述兩個自定義函數,一個是SumByColor,可以對區域按指定單元格的顏色求和。另一個是CountByColor,可以統計區域中某種顏色的個數。這兩個自定義函數都有兩個參數,前一個參數指定包含某種顏色的單元格,后一個參數為求和或計數區域。
3.關閉VBA編輯器。
使用方法:假如要求和或計數的區域在A1:B10區域中。
求出該區域中單元格底紋顏色為紅色的所有單元格數值之和,在單元格中輸入公式:
=sumByColor(A1,A1:B10)
求出該區域中單元格底紋顏色為紅色的所有單元格的個數,在單元格中輸入公式:
=CountByColor(A1,A1:B10)






