javascriptgoogle-sheetsgoogle-apps-scripttriggers

Google Sheets onEdit function


On a spreadsheet that I use daily, in Excel I had a macro that would automatically move a whole row of data if the cell in column F said "Cleared". I'm relatively comfortable with Visual Basic, however in moving to Google Sheets I understand that Javascript is used which I've never used before.

I found some code that someone else had written and changed the variables to what they need to be to run in my sheet however it's telling the that the "source" property cannot be read in line 6 of the code (and presumably line 7 also).

I'd appreciate any help that you can provide with this and will put "Learn Javascript" on my to do list!

function onEdit(event) {
// assumes source data in sheet named "Action tracker"
// target sheet of move to named "Cleared Action Points"
// test column with "Cleared" is col 6 or F
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = event.source.getActiveSheet();
var r = event.source.getActiveRange();

if(s.getName() == "Action tracker" && r.getColumn() == 6 && r.getValue() == "Cleared") {
    var row = r.getRow();
    var numColumns = s.getLastColumn();
    var targetSheet = ss.getSheetByName("Cleared Action Points");
    var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
    s.getRange(row, 1, 1, numColumns).moveTo(target);
    s.deleteRow(row);
    }
}

Solution

  • The problem is that "source" is not defined as anything as far as I can see.

    Also as mentioned before you need the variable event that you feed into the function.

    function onEdit() {
    // assumes source data in sheet named "Action tracker"
    // target sheet of move to named "Cleared Action Points"
    // test column with "Cleared" is col 6 or F
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var s = ss.getActiveSheet();
      var r = ss.getActiveRange();
      var rows = r.getRow();
      var cell = s.getRange(rows, r.getColumn());
    
    if(s.getName() == "Action Tracker" && r.getColumn() == 6 && cell.getValue() == "Cleared") {
      var numColumns = s.getLastColumn();
      var targetSheet = ss.getSheetByName("Cleared Action Points");
      var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
      s.getRange(rows, 1, 1, numColumns).moveTo(target);
      s.deleteRow(rows);
    }
    

    }

    Also, you don't need to run this function from anywhere - onEdit is a trigger and will automatically run your script if you edit something in your spreadsheet.

    Hope this helps.