Home > Mobile >  OnEdit Cell Index not working with multiple inputs
OnEdit Cell Index not working with multiple inputs

Time:02-11

I'm trying to write a piece of code that whenever someone on our rosters is terminated it will capture their data, put them into a "termed associates" sheet and delete them from the roster.

The code I wrote works fine for single instances of the change (though it is a bit slow), but the main problem is if I change multiple people to "TERM" in quick succession, it breaks and sometimes will delete rows that aren't the row meant to be deleted.

Here's my code:

    const ss = SpreadsheetApp.getActiveSpreadsheet();
    const termSheet = ss.getSheetByName('Term Tracker');
    const check = SpreadsheetApp.getActiveSheet().getActiveCell().getValue();

    function deleteTerm() {
    if(check == 'TERM'){

    //grabs the cell that has just been edited, finds the index of the row
    let sheet = ss.getActiveSheet();
    let cell = ss.getActiveCell();
    let index = cell.getRowIndex();

    //grabs data and posts to new sheet
    //grabs values to inset into email
    let read = sheet.getRange(index,1,1,55).getValues();
    let name = sheet.getRange(index, 4).getValue();
    let shift = sheet.getRange(index,1).getValue();
    termSheet.insertRowBefore(2);
    termSheet.getRange(2,1,1,55).setValues(read);

    //deletes the index row
    sheet.deleteRow(index)

    //mails me a notification someone was termed
    MailApp.sendEmail({
    to: "{myemail}",
    subject: "New Term, "   name ,
    body: "There is a new term of "   name   ", please confirm the term reason and term date. 
    They are on the "   shift   " roster"
    });

    }}
    

Any ideas on exactly what I'm doing wrong? I'm still very new to coding, so I'm sure that the code isn't very great. Any feedback would be lovely as well. :)

CodePudding user response:

This should work faster

But any expectation of consistently fast response for an onEdit function is a hopeless wish that is not going to be fulfilled. You must be patient and give it time to operate.

function onEdit(e) {
  const sh = e.range.getSheet();
  const tsh = e.source.getSheetByName('Term Tracker');
  if (e.value == 'TERM') {
    let vs = sh.getRange(e.range.rowStart, 1, 1, 55).getValues();
    let name = vs[0][3];
    let shift = vs[0][0];
    tsh.insertRowBefore(2);
    tsh.getRange(2, 1, 1, 55).setValues(vs);
    sh.deleteRow(e.range.rowStart);
    MailApp.sendEmail({to: "{myemail}",subject: "New Term, "   name,body: "There is a new term of "   name   ", please confirm the term reason and term date. They are on the "   shift   " roster"});
  }
}
  • Related