Home > Software design >  Sum two columns and display on third column
Sum two columns and display on third column

Time:10-24

I want to sum two columns that have numerical values and display the results on the third column. I have the script below but that deletes the two columns and display the results on the first column.

Any suggestions?

  var ss = SpreadsheetApp.getActiveSheet();
  var rng = ss.getRange('E2:F6');
  var val = rng.getValues();

  for(row=0;row<val.length;row  ) {
    val[row][0] =val[row][0] val[row][1];;
    val[row][1] = '';
  }
  rng.setValues(val)
}

CodePudding user response:

Try this instead. Just get the colum G and overwrite anything in it with the sum.

function test() {
  var ss = SpreadsheetApp.getActiveSheet();
  var rng = ss.getRange('E2:G6');  // just get the extra column
  var val = rng.getValues();

  for(row=0;row<val.length;row  ) {
    val[row][2] = val[row][0] val[row][1];
    val[row][1] = '';
  }
  rng.setValues(val)
}

CodePudding user response:

Using map:

function one() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getActiveSheet();
  const vs = sh.getRange('E2:F6').getValues().map(r => [r[0],r[1],r[0] r[1]]);
  sh.getRange(2,5,vs.length,vs[0].length).setValues(vs);
}
E F G
1 COL5 COL6
2 5 6 11
3 6 7 13
4 7 8 15
5 8 9 17
6 9 10 19
  • Related