Search code examples
javascriptgoogle-apps-scriptgoogle-sheetsgoogle-sheets-formula

Get the sum of values based on their background color - Google Sheets


It is possible in a google sheet to sum a row of data based on the formatting something like :

sumif(a1:d1, if background is green)

Solution

  • Explanation:

    I think the only way to achieve your goal is to use Google Apps Script and in particular custom functions.

    The following custom function totalColor(cells,color) accepts a cell or a range of cells you want to check and a color of your choice.

    Here is the list of all available colors:

    redberry, red, orange, yellow, green, cyan, cornflowerblue, blue, purple, magenta, grey, white, black

    The function returns the total sum of values of the cells for which the background colors are one of the chosen color.


    Solution:

    function totalColor(cells,color) {
        
    const jsonColor = {
        redberry: [ '#980000','#e6b8af','#dd7e6b','#cc4125','#a61c00','#85200c','#5b0f00'],
        red: [ '#ff0000','#f4cccc', '#ea9999','#e06666','#cc0000','#990000','#660000' ],
        orange:[ '#ff9900','#fce5cd','#f9cb9c','#f6b26b','#e69138','#b45f06','#783f04' ],
        yellow: [ '#ffff00','#fff2cc','#ffe599','#ffd966','#f1c232','#bf9000','#7f6000' ],
        green: [ '#00ff00','#d9ead3','#b6d7a8','#93c47d','#6aa84f','#38761d','#274e13' ],
        cyan:  [ '#00ffff','#d0e0e3','#a2c4c9','#76a5af','#45818e','#134f5c','#0c343d' ],
        cornflowerblue: [ '#4a86e8','#c9daf8','#a4c2f4','#6d9eeb','#3c78d8','#1155cc','#1c4587' ],
        blue:[ '#0000ff','#cfe2f3','#9fc5e8','#6fa8dc','#3d85c6','#0b5394','#073763' ],
        purple: [ '#9900ff','#d9d2e9','#b4a7d6','#8e7cc3','#674ea7','#351c75','#20124d' ],
        magenta: [ '#ff00ff','#ead1dc','#d5a6bd','#c27ba0','#a64d79','#741b47','#4c1130' ],
        grey:["#666666", "#999999", "#b7b7b7", "#cccccc", "#d9d9d9", "#efefef", "#f3f3f3"],
        white: ["#ffffff"],
        black: ["#000000"]
      };  
      
    const colorArr = jsonColor[color]; 
    const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
    const range = sheet.getRange(cells);
    const hex_array = range.getBackgrounds().flat();
    const values = range.getValues().flat();
    var total = 0; 
    hex_array.forEach((h,i)=>{                    
      if(colorArr.includes(h)){
      total += values[i];
      }                    
    }); 
    return total;  
    }
    

    and then use it as a simple formula in your sheet by defining the cell or the range of cells and the color with "", for example:

    =totalColor("A1:D1", "green")
    

    example


    Instructions how to create a custom function:

    1. Click on Tools => Script editor:

    setup

    1. Copy & Paste the aforementioned code snippet into the script editor and click on the save button:

    example2