如何根据第1列中的值将表格x中的行复制(然后删除)到表格y?

时间:2019-04-14 14:19:06

标签: google-apps-script google-sheets

我正在使用Google表格,并尝试设置一个Apps脚本宏

  1. 在工作表“ Sheet1”中查找在“ A”列中值为“ True”的行
  2. 复制此行并将其粘贴到工作表“ Sheet2”中最后填充的行下方的行中
  3. 删除“ Sheet1”中的行

我一直在尝试从论坛上的另一篇文章中获取代码,但是我一直在获取:TypeError:无法从未定义中读取属性“ length”。 (第20行,文件“代码”)

任何帮助将不胜感激

function copyrange() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Sheet1"); //source sheet
  var testrange = sheet.getRange("A2:AE990");
  var testvalue = (testrange.getValues());
  var csh = ss.getSheetByName("Sheet2"); //destination sheet
  var data = [];
  var j =[];

  //Condition check in G:G; If true copy the same row to data array
for (i=0; i<testvalue.length;i++) {
  if ( testvalue[i] == "TRUE") {
  data.push.apply(data,sheet.getRange(i+1,1,1,11).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);

//Delete matched rows in 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;
}
}
}

1 个答案:

答案 0 :(得分:0)

尝试一下:

function moveRows() {
  var ss=SpreadsheetApp.getActive();
  var ssh=ss.getSheetByName('Sheet1');
  var dsh=ss.getSheetByName('Sheet2');
  var srg=ssh.getDataRange();//You might want to specify a more unique range. This just gets all of the data on the sheet
  var svA=srg.getValues();
  var d=0;//deleted row counter
  //I  assume one row for a header
  for(var i=1;i<svA.length;i++) {
    if(svA[i][0].toString().toLowerCase()=='true') {
      dsh.appendRow(svA[i]);//append entire row to Sheet2
      ssh.deleteRow(i-d+1);//accounts for the difference between length of array and number of remaining row.
      d++;
    }
  }
}