Home > OS >  Increment cell value onEdit
Increment cell value onEdit

Time:08-14

I am trying to increment a cell in column B, that is on the same row as a cell in column F, when this last cell is edited. This is what I've come up with:

function clicker(e) {
  var ss = e.range.getSheet();
  var ss_name = ss.getName();
  if ((ss_name == "Report 1") && (e.range.getColumn() == 6)) {
    var row = e.range.getRow();
    var value = e.getRange(row, 2).getValue();
    value  ;
    e.range.setValue(value);
  }
}

This is the sheet: https://docs.google.com/spreadsheets/d/1AJYVX0xHwdqBbg_8aDbrS1kuOFzWs6dB7x7I-tA6vYw/edit?usp=sharing

Unfortunately, the cell value does not increment, as desired. I think that the error is in the second part of the code, within the second curly brackets, but I can't put my finger on it.

I have followed this and this as references to try and solve my issue.

CodePudding user response:

Increment B on edit of F

function onEdit(e) {
  const sh = e.range.getSheet();
  if (sh.getName() == "Report 1" && e.range.columnStart == 6) {
    e.range.offset(0, -4).setValue(e.range.offset(0, -4).getValue()   1);
  }
}

CodePudding user response:

Your code is trying to put the incremented value in column F when you probably want to put it in column A. To run the function when a cell is hand edited, use a simple trigger, like this:

/**
* Simple trigger that runs each time the user hand edits the spreadsheet.
*
* @param {Object} e The onEdit() event object.
*/
function onEdit(e) {
  if (!e) {
    throw new Error(
      'Please do not run the onEdit(e) function in the script editor window. '
        'It runs automatically when you hand edit the spreadsheet.'
    );
  }
  clicker_(e);
}


/**
* Increments a cell in 'Report 1'!B2:B when a cell in 'Report 1'!F2:F is
* hand edited.
*
* @param {Object} e The onEdit() event object.
*/
function clicker_(e) {
  let sheet;
  if (e.range.columnStart !== 6
    || !(sheet = e.range.getSheet()).getName().match(/^(Report 1)$/i)
  ) {
    return;
  }
  const range = sheet.getRange(e.range.rowStart, 2);
  range.setValue((Number(range.getValue()) || 0)   1);
}
  • Related