VBA macros · Formatting

VBA function to sum cells by background color in Excel

A user-defined function, SumByColor, that adds up the numbers in cells whose fill colour matches a sample cell. Text and empty cells are ignored.

Windows + Mac

If you mark rows by colour, sooner or later someone asks for the total of the green ones. Excel's SUMIF works with values, not colours, so you need a small function of your own. =SumByColor(range, sample cell) adds up the numbers in all cells whose fill colour matches the sample, skipping text and blanks just like SUM does.

VBA
Option Explicit

Function SumByColor(dataRange As Range, colorCell As Range) As Double
    ' Adds the numbers in dataRange whose fill colour equals the fill of colorCell
    Dim c As Range, rng As Range
    Dim target As Long

    Application.Volatile
    target = colorCell.Cells(1, 1).Interior.Color

    Set rng = Intersect(dataRange, dataRange.Worksheet.UsedRange)
    If rng Is Nothing Then Exit Function

    For Each c In rng.Cells
        If c.Interior.Color = target Then
            Select Case VarType(c.Value)
                Case vbDouble, vbCurrency, vbDate      ' numbers only, like SUM
                    SumByColor = SumByColor + CDbl(c.Value)
            End Select
        End If
    Next c
End Function
Sum numbers by fill colour

How to use it

  1. Open the workbook and press Alt+F11 (Mac: Opt+F11 or Fn+Opt+F11) to open the VBA editor. See The Developer tab and the VBA editor if you have never used it.
  2. Choose Insert › Module and paste the code. A function must live in a normal module, not in a sheet module or ThisWorkbook.
  3. Go back to Excel and type the function into a cell like any built-in function, for example =SumByColor(C2:C50, F2). It also appears in the function list when you start typing =SumByColor.
  4. Save the file as an Excel Macro-Enabled Workbook (.xlsm). A normal .xlsx file throws the code away when you save it.

A function stored in PERSONAL.XLSB works too, but then every formula has to call it as =PERSONAL.XLSB!SumByColor(...), and the formula breaks when you send the file to someone else. For functions it is usually better to keep the code inside the workbook that uses it, or to save it as an add-in (.xlam). See User-defined functions (UDFs): your own worksheet functions for more about writing your own functions.

How it works

The structure is the same as VBA function to count cells by background color in Excel: read the sample cell's fill colour once, limit the range to the used area with Intersect, and loop through the cells. The difference is what happens on a match.

Only real numbers are added. VarType(c.Value) tells what kind of value a cell holds: vbDouble for ordinary numbers, vbCurrency for cells with a currency format and vbDate for dates. Text, logical values, empty cells and errors fall through the Select Case and are ignored, which mirrors how SUM treats a range. A simpler IsNumeric test would wrongly include TRUE and numbers stored as text.

CDbl turns the value into a plain number before adding it, and the function returns a Double, so the result can be formatted in the cell like any other number. As with the counting function, Application.Volatile lets F9 update the total after you change colours, since colouring alone does not recalculate. See User-defined functions (UDFs): your own worksheet functions and Variables and data types: Dim, Option Explicit and scope.

Change it

To total by font colour, change both Interior.Color lines to Font.Color. To add the values of a different column than the coloured one, for example when the names in column A are coloured and the amounts are in column D, add a third argument and use the same row:

VBA
Function SumByColorOffset(colorRange As Range, colorCell As Range, sumColumn As Range) As Double
    Dim c As Range, v As Variant
    Dim target As Long
    Application.Volatile
    target = colorCell.Cells(1, 1).Interior.Color
    For Each c In colorRange.Cells
        If c.Interior.Color = target Then
            v = sumColumn.Worksheet.Cells(c.Row, sumColumn.Column).Value
            If VarType(v) = vbDouble Or VarType(v) = vbCurrency Then SumByColorOffset = SumByColorOffset + v
        End If
    Next c
End Function
Colour in one column, amounts in another

Use it as =SumByColorOffset(A2:A50, H2, D2): the third argument only says which column holds the amounts. To average instead, keep both a sum and a count inside the loop and return total / n when n > 0.

What can go wrong

Watch out. Conditional formatting colours are invisible to the function, for the same reason as in VBA function to count cells by background color in Excel. If the colour comes from a rule, sum with the rule's condition using SUMIF or SUMIFS instead.

The total does not update the moment you recolour a cell. Press F9 (Mac: Fn+F9 or Cmd+=), or edit any cell, and it recalculates. Cells that contain error values are skipped silently, unlike SUM, which would return the error. If that could hide problems, check the range with =SUMPRODUCT(--ISERROR(C2:C50)) next to the total.

Tip. Works on Windows and Mac. Keep the code in the workbook that uses it (or in an add-in) so the formulas keep working when you share the file.

Related: VBA function to count cells by background color in Excel, SUMIF, User-defined functions (UDFs): your own worksheet functions.

More vba macros