[英]Copy data from one sheet to another based on a specific key value
I am trying to copy data from one sheet to another in Google Docs using a script. 我正在尝试使用脚本将数据从一个工作表复制到Google文档中的另一个工作表。 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".
如果列A中的值为“名称”,我想将信息从第一张纸复制到第二张纸。 I have basic knowledge of JavaScript and so far have managed to come up with the following.
我具有JavaScript的基本知识,到目前为止,我们已经设法提出以下建议。
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.
TypeError:无法从未定义中读取属性“ length”。 (line 13, file "Code")
(第13行,文件“代码”)
Likely source of the problem: 问题的可能根源:
taget.push(data[n]);// copy the whole row
^^^^^
You probably meant target
. 您可能是指
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. 由于您从未将任何内容推入
target
,因此没有定义target[0]
,因此它当然没有length
属性。
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
. 即使修复了
taget
,也有可能发生此错误,除非您保证没有具有length
属性的target[0]
,或者当target.length === 0
时跳过该操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.