0

I wrote the code below to grab a portion of a column of numbers and add them up. However, the function is concatenating numbers rather than adding.

I'm getting this result:

0AMOUNT120123126129132135138141144147

But if I run it from Dec on the sum should be: 432

My code in Google Scripts:

//add sum and input it into the total column
function sum(startMonth, startColumn, lastRow){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  startColumn = startColumn +1;
  var sum = 0;
  var currAmount = 0;
  var k = 0;
  for(k = startMonth; k <= lastRow; k++){
   currAmount = sheet.getRange(k, startColumn).getValue();
   sum += currAmount;   //currAmount + sum;
   Logger.log(sum);
  }
  SpreadsheetApp.getActiveSheet().getRange(k, startColumn).setValue(sum);
  SpreadsheetApp.getActiveSheet().getRange(k, startColumn).setBackground("Yellow");
  return sum;
}

And a snapshot of my sheet: enter image description here

shrys
  • 5,860
  • 2
  • 21
  • 36
Katie Melosto
  • 1,047
  • 2
  • 14
  • 35

1 Answers1

0

Your result is the hint: That's not a number being added. That's strings being concatenated.

   currAmount = sheet.getRange(k, startColumn).getValue();
   sum += currAmount;   //currAmount + sum;

Specifically, this is the main problem. Regardless of whether the number returned by getValue() is a number or not, you add it to sum.

A few ways to fix this would be to adjust the value of k, to check the typeof the value, or coerce the value into a number, depending on exactly what you're trying to do. This is essentially a javascript problem, with the canonical answer here

Also, generally you should batch operations where possible; e.g., instead of running getRange().getValue() every go through a for-loop, you are much better using (as an example, may need tweaking)

var amounts = sheet.getRange(startMonth, startColumn, (lastRow - startMonth), 1);
for(var k = startMonth; k <= lastRow; k++){
 sum += amounts[k][0]
 Logger.log(sum);
}
sinaraheneba
  • 781
  • 4
  • 18