ArBaldryan
ArBaldryan

Reputation: 1

Replace or append row on edit

I have two sheets in a google spreadsheet where sheet2 needs to be updated on Edit when sheet1 is edited.

If Column A in Sheet1 is unchanged and Columns C or D are updated, the row in sheet 2 should be updated (the raw should be replaced with the last updated data)

If column A in Sheet1 is changed then a new row should be appended.

Could you please advise how the code would look like in google script onEdit?
Many thanks in advance!

Upvotes: 0

Views: 603

Answers (1)

Cooper
Cooper

Reputation: 64120

Try this:

function onEdit(e) {
  const sh = e.range.getSheet();
  if (sh.getName() == "Sheet2" && e.range.columnStart > 2 && e.range.columnStart < 5) {
    let ush = e.source.getSheetByName("Sheet1");
    ush.getRange(e.range.rowStart, e.range.columnStart).setValue(e.value);
  }
  if (sh.getName() == "Sheet2" && e.range.columnStart == 1) {
    let ush = e.source.getSheetByName("Sheet1");
    ush.appendRow(sh.getRange(e.range.rowStart, 1, 1, sh.getLastColumn()).getValues()[0]);
  }
}

Please note you cannot run this from the script editor unless you provide the event object.

Upvotes: 1

Related Questions