-1

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?

function test2() {
  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)
}
Rubén
  • 34,714
  • 9
  • 70
  • 166

2 Answers2

1

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
Cooper
  • 59,616
  • 6
  • 23
  • 54
0

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)
}
TheWizEd
  • 7,517
  • 2
  • 11
  • 19
  • Thanks for this. It works by displaying the results on the third column. However, it still deletes the two first columns with the initial values. If I take this line from the script `val[row][1] = '';`, then it works. Thanks! – nicolas94estevao Oct 23 '22 at 14:52
  • It should not delete the first but you showed it deleting the second with `val[row][1] = '';`. – TheWizEd Oct 23 '22 at 14:59