Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google spreadsheet: Sum of all bold cells

I'm trying to learn scripting in Google Spreadsheet, and I have gotten some simple scripts to work, but this one is a real pain.

I want to make a script that uses the onEdit() function to update a specific cell to show the sum of all bold values in the spreadsheet.

Fx:

1 2 3

4

Then the cell would have a value of (3+4) 7.

Hope it makes sense!

like image 664
Dennis Sødal Christensen Avatar asked Jan 15 '23 13:01

Dennis Sødal Christensen


1 Answers

It's a bit late, but it's worth an answer and I've been working on a similar question.

The formula to use is:

=sumIfBold(A1:B4,COLUMN(A1), ROW(A1))

The script is:

/**
 * Sums cell values in a range if they are bold. The use of startcol and startrow
 * is to enable the formula to be copied / dragged relatively in the spreadsheet.
 * 
 * @param  {Array.Array} range    Values of the desired range
 * @param  {int} startcol The column of the range
 * @param  {int} startrow The first row of the range
 * 
 * @return {int}          Sum of all cell values matching the condition
 */
function sumIfBold(range, startcol, startrow){
  // convert from int to ALPHANUMERIC 
  // - thanks to Daniel at http://stackoverflow.com/a/3145054/2828136
  var start_col_id = String.fromCharCode(64 + startcol);
  var end_col_id = String.fromCharCode(64 + startcol + range[0].length -1);
  var endrow = startrow + range.length - 1

  // build the range string, then get the font weights
  var range_string = start_col_id + startrow + ":" + end_col_id + endrow
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var getWeights = ss.getRange(range_string).getFontWeights();

  var x = 0;
  var value;
  for(var i = 0; i < range.length; i++) {
    for(var j = 0; j < range[0].length; j++) {
      if(getWeights[i][j].toString() == "bold") {
        value = range[i][j];
        if (!isNaN(value)){
          x += value;
        }
      }
    }
  }
  return x;
}
like image 174
Tom Horwood Avatar answered Jan 17 '23 11:01

Tom Horwood