在一行中根据值整体移动行

时间:2019-03-15 18:12:56

标签: google-apps-script

我有一个脚本设置,可以将一个工作表中的所有记录移动到另一个工作表中。但是,我想添加功能以仅移动在特定列(当前情况的列I)中具有“已批准”值的记录。我还看到了其他一些问题/答案,可以根据值移动单个行,但是我还没有弄清楚如何利用这些脚本在整个电子表格中运行。我的猜测是我可以使用for循环,但是如何?

当前脚本:

 function MoveRecords(){

  //Original Sheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Example Input")

  //Calculate # of Rows Ignoring Blank Array Values
  var Rows = ss.getRange("A2:A").getValues();
  var NumRows = Rows.filter(String).length;

/*Add a For Loop here to only get the rows with Approved in Column I?*/

  //Parsed Data to Move
  var rangeValues1 = sheet.getRange(2,1,NumRows,1).getValue();
  var rangeValues2 = sheet.getRange(2,2,NumRows,5).getValues();

  //Destination of Parsed Data 
  var DestinationSS = SpreadsheetApp.openById('ID');
  var DestinationSheet = DestinationSS.getSheetByName('Approved');  
  var DestinationLastRow = DestinationSheet.getLastRow()+1;

  //Move the Data
  DestinationSheet.getRange(DestinationLastRow,3,NumRows,1).setValue(rangeValues1);
  DestinationSheet.getRange(DestinationLastRow,5,NumRows,5).setValues(rangeValues2);

  };

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以获取所有值,为已批准过滤每一行,然后将这些行写入目标表。

function MoveRecords() {
  //Original Sheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Example Input');
  var values = sheet.getDataRange().getValues();

  /*Add a For Loop here to only get the rows with Approved in Column I?*/
  // col I = index 8
  var res = values.filter(function(row) {
    return row[8] == 'Approved';
  });

  //Parse Data to Move
  var rangeValues1 = res.map(function(row) {
    return [row[0]];
  });
  var rangeValues2 = res.map(function(row) {
    row.shift();
    while (row.length > 5) row.pop();
    return row;
  });

  //Destination
  var DestinationSS = SpreadsheetApp.openById('ID');
  var DestinationSheet = DestinationSS.getSheetByName('Approved');
  var DestinationLastRow = DestinationSheet.getLastRow() + 1;

  //Move the Data
  DestinationSheet.getRange(DestinationLastRow, 3, rangeValues1.length, 1).setValues(rangeValues1);
  DestinationSheet.getRange(DestinationLastRow, 5, rangeValues2.length, 5).setValues(rangeValues2);
}