The VBA feature of MS Excel makes it possible to sum cells based on their background color. Summing cells based on background color could save lots of time and add a lot of value to the task at hand.
Consider the example below.
The table above demonstrates all annual healthcare expenses for an individual. The cells that have a light green back ground color are the expenses that the individual paid themselves but eventually got reimbursed for by their insurance firm. As you could see the last row of the table sums up all expenses for each month irregardless of the background color of the cells.
Here are four simple steps that would allow us to do the sum based on the background of the cells so that we could know how much of the expenses have been covered by insurance and what amount hasn’t. 1. Go to the "Developer" tab and left click on “Visual Basic”. If your developer tab is not visible click here to learn how to activate it.
2. While at the VBA screen, select “Insert” and the left click on “Module”
3. Copy and paste the code below in the code screen:
Function SumByColor(CellColor As Range, rRange As Range) Dim cSum As Long Dim ColIndex As Integer ColIndex = CellColor.Interior.ColorIndex For Each cl In rRange If cl.Interior.ColorIndex = ColIndex Then cSum = WorksheetFunction.Sum(cl, cSum) End If Next cl SumByColor = cSum End Function
4. Return to the excel tab and type the following formula. and try using the "SumByColor" formula as demonstrates below:
In the screenshot above the SumByColor formula is activated and the first cell used in the formula is a reference to the background color that you wish to be summed. I chose cell $B$11 as the reference. the purpose of the dollar sign ($) is so that the reference wouldn't change after dragging the formula to other cells. As you could see the only amount that has been summed for the month of January using the SumByColor sum statement is the amount that has the light green background color.
Here is how the table would look like once the formula is applied for all 12 months.
2 Comments
Sheikh
6/5/2018 08:43:10 am
can this formula be extended on visible cells only. suppose if we filter and can it still sumbycolor.
Reply
Hi Sheikh,
Reply
Your comment will be posted after it is approved.
Leave a Reply. |
CategoriesArchives
June 2020
|