2

I have a google script function that gets me a range from a google spreadsheet.

function getGrainWeights() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  return range = ss.getRangeByName("Brew_Grains");
}

This range is then processed by another function which modifies and upadtes the values in the range.

"Brew_Grains" is a named range in my spreadsheet but I would like to replace it with a discrete range such as "B2,C3,D10" etc. Is this possible, or is there some workaround? Cheers

Phrogz
  • 296,393
  • 112
  • 651
  • 745
user1650538
  • 228
  • 1
  • 9

2 Answers2

3

You have the following ways to get a range, in addition to the named range used getRangeByName(name).

Get a range

You can find the documentation.

UPDATE

A workaround to what you want to do can be something like:

  ...
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
  var ranges = [];
  var range = ss.getRange('B2:C3');
  ranges.push(range);
  range = ss.getRange('D10');
  ranges.push(range);
  processingFunction(ranges);
  ...

You can then pass the array (ranges) to any other function for processing.

wchiquito
  • 16,177
  • 2
  • 34
  • 45
  • 1
    As far as I can work out, getRange(a1Notation) only allows getting a single cell at a time - i.e. I cannot get "B2,C3,D10" as a range? The other methods refer to getting continuous ranges? My current work around is to pass multiple continuous ranges into an array, then do something with that array, then pass the updated array values back to the ranges - a bit clunky! – user1650538 Aug 18 '13 at 22:48
0

You cannot (as far as I can tell) join two Range objects. However, if you have a custom function that operates on multidimensional arrays, you can convert the ranges into arrays and concatenate those.

For example:

function SUM_RANGE_COLUMN(myRange,colIndex){
  var val,sum=0;
  for (var i=0;i<myRange.length;i++) if (val=myRange[i][colIndex]) sum+=val;
  return sum;
}

function UNION(range1,range2){
  return range1.concat(range2);
}

With the above as custom functions, you can write this in your spreadsheet:

=SUM_RANGE_COLUMN( UNION(E4:F5,E9:F12), 1 )

To convert two real Ranges to arrays, use getValues():

function joinRanges( range1, range2 ){
  return range1.getValues().concat( range2.getValues() );
}
Phrogz
  • 296,393
  • 112
  • 651
  • 745