Google-sheets – TypeError – Move row from one sheet to another

google sheetsgoogle-apps-script

I am experiencing the following issue and was wondering if anyone with more experience can shed some light. I have very little experience with code.

Row is transferring correctly, but I am getting the following error message:

TypeError: Cannot read property 'length' of undefined (line 21, file "Code")

How do I refine the length? Do I need to?

function onEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('OpenOrders'); //source sheet
  var testrange = sheet.getRange('A:A'); //range to check
  var testvalue = (testrange.getValues());
  var csh = ss.getSheetByName('Shippedorders'); //destination sheet
  var data = [];
  var j =[];

  //Condition check in A:A; If true copy the same row to data array
for (i=0; i<testvalue.length;i++) {
  if ( testvalue[i] == 'yes') {
  data.push.apply(data,sheet.getRange(i+1,1,1,25).getValues());
    
  //Copy matched ROW numbers to j
  j.push(i);
 }
 }
//Copy data array to destination sheet

 csh.getRange(csh.getLastRow()+1,1,data.length,data[0].length).setValues(data); // line 21

//Delete matched rows in the source sheet
  for (i=0;i<j.length;i++){
  var k = j[i]+1;
  sheet.deleteRow(k);

//Alter j to account for deleted rows
  if (!(i == j.length-1)) {
  j[i+1] = j[i+1]-i-1;
}
}
}

Best Answer

The error occurs because data[0] is undefined and that might happen when Column A hasn't any `yes'.

Since you are using a onEdit trigger add the following before line 21

if(!data[0]) return;

The above line will terminate your script if data[0] is undefined