0
votes

I am trying to write a google app script so I can copy a few columns (C and D) from my main report sheet to a different sheet, based on the value of column M if that's equal to 0.

As shown in the pic below: enter image description here

So I want to copy the "Name" and "Variety" columns into another sheet where the "Germination %" column is 0.

It can be a time based trigger, that runs after every 2 hours or onEdit also. I was trying to make it a script using OnEdit, as shown below:

    function onEdit( e ){
      var sheetFrom = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("germination");
      var sheetTo = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("watering");

        var data = sheetFrom.getDataRange().getValues();
        var target = new Array();// this is a new array to collect data
        for(n=0;n<data.length;++n){ // iterate in the array, row by row
          if (data[n][12]=="0"){ // if condition is true copy the whole row to target
            target.push(data[n]);// copy the whole row
           }//if
        }//for

        //Paste to another sheet from first cell onwards
        sheetTo.getRange(1,1,target.length,2).setValues(target);
}

But I am getting errors on this "Incorrect range width, was 15 but should be 2 (line 25, file "Code")"

Line 25 is "sheetTo.getRange(1,1,target.length,2).setValues(target)"

Thanks in advance.

1

1 Answers

1
votes

In the getRange(1,1,target.length,2) method you're specifying it to select only 2 columns, change it to getRange(1,1,target.length,target[0].length) to select the array length of columns.

Update: To write only the C and D, change the target push() to:

target.push( [[data[n][2], data[n][3]] )