使用Google应用脚本将行复制到指定列值的不同工作表

时间:2016-03-10 18:41:40

标签: google-apps-script google-sheets

我正在尝试将行B和C从“MBOM”表复制到“库存”表,其中列H =“Y”。

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

function onEdit(e){
  
  var sheetFrom = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("MBOM");
  var sheetTo = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Inventory");
  
  var readinventory = sheetFrom.getDataRange().getValues();
        var target = new Array();// this is a new array to collect data
        for(n=0;n<readinventory.length;++n){ // iterate in the array, row by row
          if (readinventory[n][6]=="Y"){ // if condition is true copy row values to target
            target.push( [readinventory[n][1], readinventory[n][2]] );// copy column B and C (entire row is inventory[n])
           }
        }
        //Paste to another sheet from first cell onwards, using the array length of specifed columns
        sheetTo.getRange(1,1,target.length,target[0].length).setValues(target);
        
  
}

我做错了什么?提前感谢您的帮助!!

1 个答案:

答案 0 :(得分:0)

target不是二维数组。 setValues()需要二维数组。

以下代码使用内部数组,并在满足条件时填充内部数组。然后将内部数组添加到外部数组。外部阵列不断获得新的内部数组。每当要向其添加新值时,必须将内部数组重置为空数组。

function onEdit(e){

  var sheetFrom = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("MBOM");
  var sheetTo = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Inventory");

  var readinventory = sheetFrom.getDataRange().getValues();
  var target = new Array();// this is a new array to collect data
  var innerArray = [];

  for (n=0;n<readinventory.length;++n) { // iterate in the array, row by row
    if (readinventory[n][6]=="Y"){ // if condition is true copy row values to target
      innerArray = []; //Reset

      innerArray.push( [readinventory[n][1], readinventory[n][2]] );// copy column B and C (entire row is inventory[n])
      target.push(innerArray);
    }
  }
  //Paste to another sheet from first cell onwards, using the array length of specifed columns
  sheetTo.getRange(1,1,target.length,target[0].length).setValues(target);
};