0
votes

How would I write a script that increments the selected cells. Here is code for incrementing one selected cell. Cells will always contain natural numbers.

function increment() {
  
  var currentCell = SpreadsheetApp.getCurrentCell();
  var value = currentCell.getValue();
  currentCell.setValue(value+1);

}

I want something like this if possible

function increment(){
  var selectedCells = SpreadsheetApp.getSelectedCells();
  selectedCells.forEach( (e) => {
    e.setValue(e.getValue() + 1 );
  });

}
1

1 Answers

1
votes

Selections do not need to be contiguous, so to implement this in a generic fashion, you will have to iterate a RangeList object and use range.getValues().

The getValues() call will return a 2D array. One easy way to iterate the values in the array is to use a map.map pattern. Try this:

function increment() {
  SpreadsheetApp.getActiveRangeList()
    .getRanges().forEach(range => {
      const values = range.getValues()
        .map(row => row
          .map(value => (Number(value) || 0) + 1)
        );
      range.setValues(values);
    });
}