Search code examples
optimizationgoogle-apps-scriptsetvalue

Setting several "setValue" at once


I have some cells (that are non-adjacenet). Each of these has a range name in the form "rLampnn" as below.

  ss.getRangeByName("rLamp20").setValue(e.range.getValue());
  ss.getRangeByName("rLamp19").setValue(e.range.getValue());
  ss.getRangeByName("rLamp18").setValue(e.range.getValue());

I want to put the same value into several of them at once. (Each of them then has a conditional format which changes the cell colour depending on what was entered into them).

Is there a more efficient way (i.e. quicker) of setting the same value into a group of these cells rather than individual calls like above?


Solution

  • If you have many of them you could loop .setValue() using the nn index in the named ranges:

    var fName = 'rLamp';
    var howManyNamedRanges = 20;
    // Assuming the first NamedRange is rLamp0
    for (var i=0;i<howManyNamedRanges;i++) {
      ss.getRangeByName(fName+i).setValue(e.range.getValue());    
    }
    

    If the first named ranges is 1 or else you could change it to:

    var fName = 'rLamp';
    var firstNamedRange = 4;
    var lastNamedRange = 20;
    // Assuming the first NamedRange is rLamp[n]
    for (var i=firstNamedRange;i<=lastNamedRange;i++) {
      ss.getRangeByName(fName+i).setValue(e.range.getValue());    
    }