user3246131
user3246131

Reputation: 1

Working with Ranges in Google Apps Scripts

Im writing a simple function in Google Spreadsheets. I want to input two ranges in the argument something like this:

=EctsPartial(C3:C4, E3:E4)

For the following function I wrote:

function EctsPartial(rangeA, rangeB) {

  Logger.log(rangeA+"  "+rangeB);
  var noten = SpreadsheetApp.getActiveSheet().getRange(rangeA).getValues();
  var ects = SpreadsheetApp.getActiveSheet().getRange(rangeB).getValues();

  for(var i=0; i < SpreadsheetApp.getActiveSheet().getRange(rangeB).getHeight(); i++){

      if(noten[i] != "" && noten[i] != 5) {
      summe = summe - 0;
      ects[i] = ects[i] - 0;

      summe = summe + ects[i];
   }
    Logger.log(i+":");
    Logger.log(summe);
   } 

  return summe;  

};

But the program keeps telling me that the argument of getRange() is not correct. If I manually type "C3:C4" (including the ") it works but otherwise it doesn't. What am I doing wrong?

Upvotes: 0

Views: 167

Answers (2)

I think this is what you are trying to do. This is for custom spreadsheet functions.

In spreadsheet, the following code allows you to type =EctsPartial(C1) instead of =EctsPartial("C1"). If you put return noten on the script, it will get the value of C1

function EctsPartial(rangeA, rangeB) {
  if (rangeA.map) {
    return rangeA.map(EctsPartial);
  } else {
    var noten = rangeA;
  }
}

https://developers.google.com/apps-script/guides/sheets/functions#optimization

Upvotes: 1

wchiquito
wchiquito

Reputation: 16569

A couple of options include:

1.

=EctsPartial("C3:C4"; "E3:E4")

.gs:

function EctsPartial(rangeA, rangeB) {
  var noten = SpreadsheetApp.getActiveSheet().getRange(rangeA).getValues();
  var ects = SpreadsheetApp.getActiveSheet().getRange(rangeB).getValues();
  var sum = 0;
  noten.forEach(function(value) {
    sum += value[0];
  });
  ects.forEach(function(value) {
    sum += value[0];
  });
  return sum;
}

enter image description here

2.

=EctsPartial(C3:C4; E3:E4)

.gs:

function EctsPartial(rangeA, rangeB) {
  var sum = 0;
  rangeA.forEach(function(value) {
    sum += value[0];
  });
  rangeB.forEach(function(value) {
    sum += value[0];
  });
  return sum;
}

enter image description here

Upvotes: 0

Related Questions