Wednesday, June 16, 2010

Sum Total as Per Cell Color

Hello All !
I Logged in after a long time.... ! Hope you all are doing good and roaring in Excel as well.
Joy... from JLT... This solution is dedicated to you. After a long time, I came across someone (Joy) who was trying to ensure that he gets all his excel issues re-solved in the short stipulated time that we got to discuss on excel. Jokes apart, Joy as I promised here is a solution that can be used for adding cell values with a particular color. Though, this will not work for cell color used by conditional formatting.

Issue Description: Sum Total the cell values as per the given cell color. In this example, as per fill color of cell C2.

Refer to the SnapShot below


Solution: Developed a Macro named Sum_As_Per_Color()

Step 1: In Your Excel File, Go To Tools->Macro->Visual Basic Editor (Shortcut: Alt+F11)
Step 2: Go To Insert->Module
Step 3: Within the inserted Module, Copy Paste the below code

Sub Sum_As_Per_Color()

Dim nbr_rows As Integer, i As Integer, val As Integer, col_nbr As Integer, row_pos As Integer
Dim total As Long

total = 0 'initialise total value to 0

'Take inputs from the User

'Nbr of rows
nbr_rows = InputBox("Enter the nbr of rows")

'Col_nbr
col_nbr = InputBox("Enter the column Index Nbr with Data")

'Row Nbr where Range Starts
row_pos = InputBox("Starting Adding from what Row Nbr?")

'Fill color of Cell C2
val = Cells(2, 3).Interior.ColorIndex

For i = 1 To nbr_rows
If Cells(row_pos, col_nbr).Interior.ColorIndex = val Then
total = total + ActiveCell.Value
End If
row_pos = row_pos + 1
ActiveCell.Offset(1, 0).Select
Next i

ActiveCell.Value = total 'Print the Final sum total in the cell below the RANGE

End Sub

Step 4: Save the File & close Visual Basic Editor
Step 5: Press Alt+F8, Run the Macro with the name Sum_As_Per_Color() and verify the result.

Note: Remember that before running the Macro, select the 1st cell from the range ie. Make it active. Also, when you run the Macro, for this example hereby is a guideline for input
1. For total nbr of rows=> 12
2. Col Index would be => 5
3. Range starts at Row Nbr=> 4

Joy & Team, Remember to ask me for lunch tommorow :).............CHEERS!!

No comments:

Post a Comment