Last active
February 13, 2019 11:42
-
-
Save marcup/eb8aa3e7abc20acae181a4e9a9d9b3f8 to your computer and use it in GitHub Desktop.
Google Docs Script that gives the sum of values in cells of a sheet that match with a specified background colour
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {range} sumRange Range to be evaluated | |
* @param {range} colorRef Cell with background color to be searched for in sumRange | |
* @return {number} | |
* @customfunction | |
*/ | |
function sumMatchingColoredCells(sumRange,colorRef) { | |
var activeRange = SpreadsheetApp.getActiveRange(); | |
var activeSheet = activeRange.getSheet(); | |
var formula = activeRange.getFormula().toString(); | |
formula = formula.replace(new RegExp(';','g'),','); | |
var rangeA1Notation = formula.match(/\((.*)\,/).pop(); | |
var range = activeSheet.getRange(rangeA1Notation); | |
var bg = range.getBackgrounds(); | |
var values = range.getValues(); | |
var colorCellA1Notation = formula.match(/\,(.*)\)/).pop(); | |
var colorCell = activeSheet.getRange(colorCellA1Notation); | |
var color = colorCell.getBackground(); | |
var total = 0; | |
for(var i=0;i<bg.length;i++) | |
for(var j=0;j<bg[0].length;j++) | |
if( bg[i][j] == color ) | |
total=total+(values[i][j]*1); | |
return total; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment