根据特定键值将数据从一个工作表复制到另一个工作表

时间:2013-07-16 18:26:36

标签: javascript google-apps-script google-sheets

我正在尝试使用脚本在Google文档中将数据从一个工作表复制到另一个工作表。这两张表都是同一个电子表格文档的一部分。如果A列中的值是“Name”,我想将信息从第一张表复制到第二张表。 我有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 

当我运行上述内容时 - 我得到以下内容:

  

TypeError:无法从undefined中读取属性“length”。 (第13行,文件“代码”)

1 个答案:

答案 0 :(得分:1)

问题的可能来源:

taget.push(data[n]);// copy the whole row
^^^^^

你可能意味着target。事实上,你会遇到一个问题:

target[0].length

由于您从未向target推送任何内容,因此未定义target[0],因此当然没有length属性。

即使您修复了taget,也存在此错误的风险,除非您要么保证target[0]具有length属性,要么在{{target.length === 0时跳过操作1}}。