Reputation: 1
I am trying to copy data from one sheet to another in Google Docs using a script. Both sheets are part of the same Spreadsheet doc. I would like to copy the information from the first sheet to the second sheet if the value in column A is "Name". I have basic knowledge of JavaScript and so far have managed to come up with the following.
function copytoo(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = SpreadsheetApp.setActiveSheet(ss.getSheets()[0]);// selects the first sheet in your spreadsheet
var data = sh.getDataRange().getValues();// data is a 2D array, index 0 = col A
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][0]=="Name"){ ;// if condition is true copy the whole row to target
taget.push(data[n]);// copy the whole row
}//if
}//for
var sh2=SpreadsheetApp.setActiveSheet(ss.getSheets()[1]); //second sheet of your spreadsheet
sh2.getRange(1,1,target.length,target[0].length).setValues();// paste the selected values in the 2cond sheet in one batch write
}//function
When I run the above - I get the following:
TypeError: Cannot read property "length" from undefined. (line 13, file "Code")
Upvotes: 0
Views: 3709
Reputation: 45750
Likely source of the problem:
taget.push(data[n]);// copy the whole row
^^^^^
You probably meant target
. As it is, you'll run into a problem with:
target[0].length
Since you never pushed anything to target
, there is no target[0]
defined, so of course it has no length
property.
Even if you fix taget
, you have the risk of this error unless you either guarantee that there is a target[0]
that has a length
property, or skip the operation when target.length === 0
.
Upvotes: 1