Home > database >  Google Apps Script for moving and timestamping row in Google Sheets
Google Apps Script for moving and timestamping row in Google Sheets

Time:09-08

Let me start by saying writing scripts is not in my wheelhouse. I hobbled together my first one by by utilizing forums like this, but never really understood how it worked. Now, that script is no longer functioning and I'm stumped as to why. In addition, I'd like to add to that script, but am unsure as to how. Here's my situation and objective...

I have a spread sheet comprised of 2 sheets, and there are 2 things I'd like to happen when a specific dropdown is selected for any row.
First is for that row to move from sheet 1 to sheet 2. I achieved this by using the following script:

function onEdit(event) {
  // assumes source data in sheet named Repairs
  // target sheet of move to named Closed
  // test column with yes/no is col 4 or D
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = event.source.getActiveSheet();
  var r = event.source.getActiveRange();
  if(s.getName() == "Repairs" && r.getColumn() == 6 && r.getValue() == "Closed") {
    var row = r.getRow();
    var numColumns = s.getLastColumn();
    var targetSheet = ss.getSheetByName("Closed");
    var target = targetSheet.getRange(targetSheet.getLastRow()   1, 1);
    s.getRange(row, 1, 1, numColumns).moveTo(target);
    s.deleteRow(row);
  }
}

This worked well for sometime, but recently stopped.

In addition to getting this to work again, the second function I would like to incorporate is to add a timestamp. Ideally, once the row is moved to the 2nd sheet, I would like a column to be added that includes the time/date of the move.

If anyone is able to help with this I'd greatly appreciate it. If more detail is required please let me know and I'll do my best to provide it. Thanks for reading!

CodePudding user response:

I've modified your script to remove redundant commands. Everything you need to know about the edit is in the event object.

function onEdit(event) {
  // assumes source data in sheet named Repairs
  // target sheet of move to named Closed
  // test column with yes/no is col 4 or D
  var s = event.range.getSheet();
  if( s.getName() == "Sheet1" && event.range.getColumn() == 6 && event.value == "Closed") {
    var row = event.range.getRow();
    var numColumns = s.getLastColumn();
    var targetSheet = event.source.getSheetByName("Sheet2");
    var target = targetSheet.getRange(targetSheet.getLastRow()   1, 1);
    s.getRange(row, 1, 1, numColumns).moveTo(target);
    target.offset(0,numColumns).setValue(new Date());
    s.deleteRow(row);
  }
}

Reference

  • Related