0

I have the below script for archiving rows from one sheet to another if some conditions are met (column G is not blank, and the date in column A is equal or older than 3 months). it appends the matching row to a new sheet and deletes the row from the original sheet.

function Archiving() {

  var masterSS = SpreadsheetApp.getActiveSpreadsheet() || SpreadsheetApp.openById('sheetID');
  var responseSheet = masterSS.getSheetByName('responseSheetname');
  var archiveSheet = masterSS.getSheetByName('archiveSheetName');

  var responseData = responseSheet.getRange(2,1, responseSheet.getLastRow()-1, responseSheet.getLastColumn()).getValues();
  var lastRow = responseSheet.getLastRow();
  var today = new Date();
  for (var i = responseData.length-1; i < responseData.length; i--){
    var row = responseData[i];
    if (row[0] == "") {break;}
    if (row[6] != "") {
      var date = row[0];
      if (date != "" && ((today.getTime() - date.getTime()) > 7776000000)) {
        Logger.log(date)
        archiveSheet.appendRow(responseData[i]);
        responseSheet.deleteRow(i+2);
      }
    }
  }
}

It's working, however, when it has completed archiving, it throws out the following error:

TypeError: Cannot read property "0" from undefined. (line 42, file "Archiving Script")

I figure this because it's still trying to loop through and finding nothing, something I had hoped the break would fix, but it hasn't.

Anyone able to suggest a fix?

3
  • 1
    Try if (!row || row[0] == "") {break;} Commented May 30, 2018 at 11:35
  • 2
    It seems that there is no end of the for loop of for (var i = responseData.length-1; i < responseData.length; i--){. So how about modifying from i < responseData.length to i >= 0? Commented May 30, 2018 at 11:42
  • Looks like @LGSon hit the nail on the head, that seems to have solved it. Thanks, folks! Commented May 30, 2018 at 12:07

1 Answer 1

1

If anyone is interested, the fix was to change.

if (row[0] == "") {break;}

to

if (!row || row[0] == "") {break;}

Thanks for that LGSon.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.